Checking if array is multidimensional or not?

后端 未结 25 3216
醉话见心
醉话见心 2020-11-28 01:41
  1. What is the most efficient way to check if an array is a flat array of primitive values or if it is a multidimensional array?
相关标签:
25条回答
  • 2020-11-28 02:27

    All the above methods are too complex for quick rolling out. If an array is flat, testing the first element should return a primitive e.g int, string e.t.c. If it is multidimensional, it should return an array. By extension, you can use this one liner fast and neat.

    echo is_array(array_shift($myArray));
    

    if this returns true, the array is multidimensional. Else it is flat. Just to note, it is very rare for arrays to have different dimensions e.g. if you are generating data from a model, it will always have the same type of multidimensional or flat structure that can be traversed by loops. If it isn't, then you have custom built it by hand, which means you know where everything will be and it just works without needing to write a looping algorithm

    0 讨论(0)
  • 2020-11-28 02:31

    I think this is the most straight forward way and it's state-of-the-art:

    function is_multidimensional(array $array) {
        return count($array) !== count($array, COUNT_RECURSIVE);
    }
    
    0 讨论(0)
  • 2020-11-28 02:31

    After PHP 7 you could simply do:

    public function is_multi(array $array):bool
    {
        return is_array($array[array_key_first($array)]);
    }
    
    0 讨论(0)
  • 2020-11-28 02:32

    You could look check is_array() on the first element, under the assumption that if the first element of an array is an array, then the rest of them are too.

    0 讨论(0)
  • 2020-11-28 02:33

    I think this one is classy (props to another user I don't know his username):

    static public function isMulti($array)
    {
        $result = array_unique(array_map("gettype",$array));
    
        return count($result) == 1 && array_shift($result) == "array";
    }
    
    0 讨论(0)
  • 2020-11-28 02:34
    is_array($arr[key($arr)]); 
    

    No loops, plain and simple.

    Works also with associate arrays not only numeric arrays, which could not contain 0 ( like in the previous example would throw you a warning if the array doesn't have a 0. )

    0 讨论(0)
提交回复
热议问题