Checking if array is multidimensional or not?

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

    In addition to the previous answers and depending on the schema of the array you want to check:

    function is_multi_array($array=[],$mode='every_key'){
    
        $result = false;
    
        if(is_array($array)){
    
            if($mode=='first_key_only'){
    
                if(is_array(array_shift($array))){
    
                    $result = true;
                }
            }
            elseif($mode=='every_key'){
    
                $result = true;
    
                foreach($array as $key => $value){
    
                    if(!is_array($value)){
    
                        $result = false;
                        break;
                    }
                }
            }
            elseif($mode=='at_least_one_key'){
    
                if(count($array)!==count($array, COUNT_RECURSIVE)){
    
                    $result = true; 
                }
            }
        }
    
        return $result;
    }
    

提交回复
热议问题