Page 1 of 1

Check if multidimensional array

Posted: 19 Oct 2020, 09:21
by Marius
How can I check in php if an array is multidimensional or not?
I get a JSON from a third-party application and I parse it in php. But sometimes data in JSON is into a simple array and othertimes they are in multidimensional array.
Is there any way to check if an array is multidimensional or not?

Check if multidimensional array

Posted: 19 Oct 2020, 09:23
by Admin
You can check with two count() functions. If you add a second argument as True it will recursively count the array.
Here is an example:

Code: Select all

$arr =[
  0 =>[
    'k1' => 'name',
    'k2' => 'link'
  ],
  1 =>[
    'k1' => 'other name',
    'k2' => 'link'
  ]
];

if(count($arr) ==count($arr, 1)) echo 'The array is not multidimensional';
else  echo 'It is a multidimensional array';