How to find out if an array is multidimensional or not in PHP?

0

I have these two arrays below:

 $a = [1, 2, 3];

 $b = [1,[2, [3, 4]]];

I know that $a is a% one-dimensional%, and array , multidimensional (arrays array).

Now, how would I find out, through a function, that I returned $b , which one is multidimensional and which is not?

I want to detect if an array has any item with a boolean (this would already be considered multidimensional).

    
asked by anonymous 12.08.2016 / 20:16

2 answers

3

One way to be able to know this is to use array_map() to apply the is_array() function on each element of the main array and add the elements of the return array, if zero is a simple array if greater than one is a multidimensional array.

<?php
   $b =  [1,[2, [3, 4]], ['a']];
   //$b =  [1,2,3];
   $a = array_sum(array_map('is_array', $b));
    
12.08.2016 / 20:31
2

A possible technique would be to use count to count the values of array and then compare with count using the second parameter COUNT_RECURSIVE .

But this method has a flaw. If array is empty, we will have an unexpected return:

$a = [1, 2]

$b = [1, []]

count($a) == count($a, COUNT_RECUSIVE); // true, não é multidimensional

count($b) == count($b, COUNT_RECUSIVE); // true, mas está errado, pois pelo fato de o 'array' está vazio, não conta recursivamente.

So what's the solution?

I thought of using the gettype function combined with array_map to circumvent the situation:

 in_array("array", array_map('gettype', $a));

 in_array("array", array_map('gettype', $b));

The gettype function will return the type name of the passed value. Combining with array_map , it will use this function on each element of array , returning a array of variable type names.

The only solution is to check that the word "array" is within that array generated. If so, it is multidimensional.

For performance issues shown in the PHP manual itself regarding gettype function, we can replace it with is_array . But we would have to check if true exists in the new array generated by array_map .

in_array(true, array_map('is_array', $b), true)
    
12.08.2016 / 20:29