Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I was wondering if it is always necessary to use something like is_array() before every foreach i do.

In case the variable is not an array, it throws an error. So i always use:

if(is_array($users))   {
    foreach($users as $user){

    }
}

What would you recommend me? Thanks.

like image 456
Alvaro Avatar asked Jun 22 '12 13:06

Alvaro


People also ask

What is the use of Is_array () function?

The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.

Can you do a forEach on empty array?

The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.


1 Answers

Well if you know your code well enough, there should be no reason to have to check if it is an array.

Otherwise, if the variable changes type that often I would suggest tweaking your code a bit so it does not do that.

Other than that, using that if statement is the way to go.

like image 169
Naftali Avatar answered Oct 17 '22 13:10

Naftali