Saturday, November 28, 2015

Is it always necessary to use "is_array()" before a foreach?

Many times I see a code, that fails because of one simple and very common programmer mistake.
Programmers often use variabled in foreach() construction without validation before.

This mistake may leads to unstable work of your code.
It must be a "golden" rule of every PHP programmer to always use a validation of  variable before running foreach() construction.

You may do it in few ways:

1. Direct validation:
if(is_array($users))   {
    foreach($users as $user){

    }
} 


2. Casting (not recommended, you know why, right?):
foreach((array)$users as $user){

} 

such way is better, but still...:
$users = (array)$users;
foreach($users as $user){

} 


3. Your own function for handling such cases:
function actionHandelingUsers($users)
{
    if(!is_array($users))
    {
        throw new Exception('$users must be an array');
    }

    foreach($users as $user){
        ...
    }
}

Ok, but sometimes I hear a following argument: my function is always returns an array, why do I need to perform a validation?

The answer is simple: there is no always in programming - what if I decide to change yuor function output? What will be with yuor code after the function will return TRUE instead of array()? You know, right - your code will crash...

The same answer about  using of empty() instead of is_array(): empty() doesn't check if the value is array... , so you may not use it in this case.

4 comments:

Bangalore Web Genius said...

Experienced web developers who have extensive knowledge in developing websites, applications, extensions and components.
Website Developers Bangalore | Web Design Bangalore

Johnson Mobley said...

The house design ideas article is all about the new tools and applications that are available in the market for kitchen design software purposes. There are many new tools coming up which will help home owners to get their home or space renovated with new home design ideas options. There are some inbuilt templates available in the market that seems to work effortlessly and house design apps in quick stance of time.

Web Development Service in India said...

Thumbs up to you. Well described. This is really helpful topic. I would like to visit your blog again. Keep update your post with creative ideas.

Shiya Priya said...

Nice Website...
Hey JOIN now fblikesbot.com and Increase Facebook Likes your profile and websites.
Increase Facebook Likes and check your website worth worth my websites
FB Likes and check your website worth Website Value Calculator
Hot Wallpapers
its may be very beneficial for you also really