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

Asked

Viewed 615 times

0

I have these two arrays down below:

 $a = [1, 2, 3];

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

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

Now, how could I discover, through a function, that returns boolean, which of them is multidimensional and which is not?

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

  • 1

    I think it’s that that search. I already needed that check, fell like a glove.

  • @Papacharlie this I know :D. Only she has a small flaw. If the array internal is empty, it will recognize that the value of count is equal

  • I couldn’t get around with a array filter? I can’t remember if I ever used the filter, then I’ll check the function.

2 answers

3

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

Only this method has a flaw. If the array have 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 I’d use the function gettype combined with array_map to get around the situation:

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

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

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

The solution is just to check whether the word "array" is inside that array generated. If yes, it is multidimensional.

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

in_array(true, array_map('is_array', $b), true)

3

One way to know that is to use array_map() to apply the function is_array() in each element of the main array and sum the elements of the return array, if zero is a simple array if it is 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));
  • I had just posted as complement kkkkk +1

  • But you understand why I thought count and `Count recursive has flaws, right?

  • @Wallacemaxters pq it counts as element?

  • In fact, people compare the recursive Count, as it will count more elements than the normal Count. Only if the internal array is empty, it will say that it is not recursive

Browser other questions tagged

You are not signed in. Login or sign up in order to post.