How to check if variable is array?… or something array-like

后端 未结 6 1676
南方客
南方客 2020-12-04 22:46

I want to use a foreach loop with a variable, but this variable can be many different types, NULL for example.

So before foreach

6条回答
  •  遥遥无期
    2020-12-04 23:39

    If you are using foreach inside a function and you are expecting an array or a Traversable object you can type hint that function with:

    function myFunction(array $a)
    function myFunction(Traversable)
    

    If you are not using foreach inside a function or you are expecting both you can simply use this construct to check if you can iterate over the variable:

    if (is_array($a) or ($a instanceof Traversable))
    

提交回复
热议问题