-1

I have two type of array.

First type

 $arr = [1,2,3];

Second type

$arr = [[1,2,3],[4,5,6],[7,8,9]];

How to check that my array is single or multi array.

I am using below code which is always giving me as Multi Array

 if(is_array($arr)){   
   echo "Multi Array"; 
 } else{   
   echo "SingleArray"; 
 }
1
  • 3
    if(is_array($arr) and is_array($arr[0])) Commented Jun 29, 2018 at 13:30

2 Answers 2

2

You are asking if you can check for your array being multi-dimensional, to which end, I came up with a function not so long ago;

<?php
function is_multidimensional(array $array)
{
    foreach ($array as $part)
    {
        if (is_array($part)) return true;
    }
    return false;
}

$is_md_array = is_multidimensional($myarray); // True if it is, false if not

There is nothing to say that this can't be made fully recursive to check further down the array too, but this is a good start if you need this more often than once

Sign up to request clarification or add additional context in comments.

2 Comments

What would be the point to 'check further down the array too'? Once a sub-array is detected you can stop, so you will never get 'further down'.
@KIKOSoftware - I have had to extend this to traverse further down the arrays, simply because I knew that the first 2 / 3 steps were going to be MD (from JSON in this case), but needed to know if after a certain level of steps it ended being MD for audit logs and trails
1

This attempt is not as good as Sam Swift's answer as it does not stop on the 1st array encountered and it can be slow with large arrays because of in_array().
But here it is:

// This will contain an array of boolean (is the item an array or not)
$are_arrays = array_map( function ($a) {
    return is_array($a);
}, $arr );

// This will return if true is found in our previous array
$is_multi = in_array(true, $are_arrays);


// Output debug
var_dump($is_multi);

It can fit into one single line for a "quick check":

$is_multi = in_array(true, array_map(function ($a) { return is_array($a); }, $arr));

3 Comments

Clever, but rather difficult to understand. It also does more work than is needed because it doesn't stop as soon as an array in an array is found.
@KIKOSoftware you are right, Sam Swift's answer is the best I think. I'll edit to mark it as "attempt" I guess
I personally really like this - it's a great example of what can be done to achieve the same result, yes a performance hit will happen with larger arrays, but for the quick checks, I love this solution, you've taught me something new, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.