Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid argument supplied for foreach()

Tags:

foreach

php

It often happens to me to handle data that can be either an array or a null variable and to feed some foreach with these data.

$values = get_values();  foreach ($values as $value){   ... } 

When you feed a foreach with data that are not an array, you get a warning:

Warning: Invalid argument supplied for foreach() in [...]

Assuming it's not possible to refactor the get_values() function to always return an array (backward compatibility, not available source code, whatever other reason), I'm wondering which is the cleanest and most efficient way to avoid these warnings:

  • Casting $values to array
  • Initializing $values to array
  • Wrapping the foreach with an if
  • Other (please suggest)
like image 544
Roberto Aloi Avatar asked Apr 13 '10 13:04

Roberto Aloi


People also ask

What Is Invalid argument supplied for foreach ()?

The "invalid argument supplied for foreach() " error​ occurs when PHP's built-in foreach() tries to iterate over a data structure that is not recognized as an array or object. // a list/array, a boolean FALSE is returned.

What is the function of foreach construct in PHP?

The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.


1 Answers

Personally I find this to be the most clean - not sure if it's the most efficient, mind!

if (is_array($values) || is_object($values)) {     foreach ($values as $value)     {         ...     } } 

The reason for my preference is it doesn't allocate an empty array when you've got nothing to begin with anyway.

like image 85
Andy Shellam Avatar answered Oct 14 '22 20:10

Andy Shellam