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.

2 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

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.