Checking if array is multidimensional or not?

后端 未结 25 3209
醉话见心
醉话见心 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:43

    Try as follows

    if (count($arrayList) != count($arrayList, COUNT_RECURSIVE)) 
    {
      echo 'arrayList is multidimensional';
    
    }else{
    
      echo 'arrayList is no multidimensional';
    }
    
    0 讨论(0)
  • 2020-11-28 02:44

    Even this works

    is_array(current($array));
    

    If false its a single dimension array if true its a multi dimension array.

    current will give you the first element of your array and check if the first element is an array or not by is_array function.

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

    For PHP 4.2.0 or newer:

    function is_multi($array) {
        return (count($array) != count($array, 1));
    }
    
    0 讨论(0)
  • 2020-11-28 02:45

    Its as simple as

    $isMulti = !empty(array_filter($array, function($e) {
                        return is_array($e);
                    }));
    
    0 讨论(0)
  • 2020-11-28 02:46
    if($array[0]){
    //enter your code 
    }
    
    0 讨论(0)
  • 2020-11-28 02:48

    All great answers... here's my three lines that I'm always using

    function isMultiArray($a){
        foreach($a as $v) if(is_array($v)) return TRUE;
        return FALSE;
    }
    
    0 讨论(0)
提交回复
热议问题