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

If you're sure that something is an array or otherwise implements Iterable, you obviously don't need the extra if condition. If you're not sure, then obviously checking the type will make your code more reliable.

Some hacks I've seen include casting the variable to an array: (array)$users. This is not recommended though, it's better to explicitly check the type.

Also, if this is code inside a function you can use argument typing:

function mycode(array $users)
{
    foreach ($users as $user) { }
}

When the function is called with the wrong type it will trigger an error.


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.