Invalid argument supplied for foreach()

后端 未结 19 1338
花落未央
花落未央 2020-11-21 06:32

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_val         


        
相关标签:
19条回答
  • 2020-11-21 06:47

    Exceptional case for this notice occurs if you set array to null inside foreach loop

    if (is_array($values))
    {
        foreach ($values as $value)
        {
            $values = null;//WARNING!!!
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:50

    How about this solution:

    $type = gettype($your_iteratable);
    $types = array(
        'array',
        'object'
    );
    
    if (in_array($type, $types)) {
        // foreach code comes here
    }
    
    0 讨论(0)
  • 2020-11-21 06:50
    foreach ($arr ?: [] as $elem) {
        // Do something
    }
    

    This doesen't check if it is an array, but skips the loop if the variable is null or an empty array.

    0 讨论(0)
  • 2020-11-21 06:51

    What about defining an empty array as fallback if get_value() is empty?
    I can't think of a shortest way.

    $values = get_values() ?: [];
    
    foreach ($values as $value){
      ...
    }
    
    0 讨论(0)
  • 2020-11-21 06:52

    How about this one? lot cleaner and all in single line.

    foreach ((array) $items as $item) {
     // ...
     }
    
    0 讨论(0)
  • 2020-11-21 06:55

    Please do not depend on casting as a solution, even though others are suggesting this as a valid option to prevent an error, it might cause another one.

    Be aware: If you expect a specific form of array to be returned, this might fail you. More checks are required for that.

    E.g. casting a boolean to an array (array)bool, will NOT result in an empty array, but an array with one element containing the boolean value as an int: [0=>0] or [0=>1].

    I wrote a quick test to present this problem. (Here is a backup Test in case the first test url fails.)

    Included are tests for: null, false, true, a class, an array and undefined.


    Always test your input before using it in foreach. Suggestions:

    1. Quick type checking: $array = is_array($var) or is_object($var) ? $var : [] ;
    2. Type hinting arrays in methods before using a foreach and specifying return types
    3. Wrapping foreach within if
    4. Using try{}catch(){} blocks
    5. Designing proper code / testing before production releases
    6. To test an array against proper form you could use array_key_exists on a specific key, or test the depth of an array (when it is one !).
    7. Always extract your helper methods into the global namespace in a way to reduce duplicate code
    0 讨论(0)
提交回复
热议问题