Checking if array is multidimensional or not?

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

    The native print_r function returns a human-readable string. Just count the "Array" instances.

    try...

    substr_count(print_r([...array...], true), 'Array') > 1;
    
    $a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
    $b = array(1 => 'a',2 => 'b');
    $c = array(1 => 'a',2 => 'b','foo' => array(1,array(2)));
    $d = array(array());
    $e = array(1, array());
    $f = array(array(), array());
    $g = array("hello", "hi" => "hi there");
    $h[] = $g;
    
    var_dump(substr_count(print_r($a, true), 'Array') > 1);
    ...
    
    //a: bool(true)
    //b: bool(false)
    //c: bool(true)
    //d: bool(true)
    //e: bool(true)
    //f: bool(true)
    //g: bool(false)
    //h: bool(true)
    

    On my box, "is_multi took 0.83681297302246 seconds in 500000 times"

    Courtesy: Ruach HaKodesh

提交回复
热议问题