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
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);
}
After PHP 7 you could simply do:
public function is_multi(array $array):bool
{
return is_array($array[array_key_first($array)]);
}
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.
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";
}
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. )