Invalid argument supplied for foreach()

后端 未结 19 1438
花落未央
花落未央 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: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

提交回复
热议问题