VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-check-an-array-is-multidimensional-or-not-in-php/

⇱ How to check an array is multidimensional or not in PHP ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to check an array is multidimensional or not in PHP ?

Last Updated : 11 Jul, 2025

Given an array (single-dimensional or multi-dimensional) the task is to check whether the given array is multi-dimensional or not.

Below are the methods to check if an array is multidimensional or not in PHP:

Using rsort() function

This function sorts all the sub-arrays towards the beginning of the parent array and re-indexes the array. This ensures that if there are one or more sub-arrays inside the parent array, the first element of the parent array (at index 0) will always be an array. Checking for the element at index 0, we can tell whether the array is multidimensional or not.

Syntax:

rsort( $array )

Parameters: The rsort() function accepts one parameter.

  • $array: This is the object you want to pass to the function.

Example 1: PHP program to check if an array is multidimensional or not using the rsort function.


Output
bool(true)

Example 2: Another PHP program to check an array is multidimensional or not using count function.


Output
bool(true)
bool(false)

Note: Try to avoid use count and count_recursive to check that the array is multi-dimension or not cause you may don't know to weather the array containing a sub-array or not which is empty.

Using Nested foreach Loop

To check if an array is multidimensional in PHP using nested foreach loop, iterate through each element and if any element is an array, return true; otherwise, return false. This method traverses all levels of nested arrays.

Example: This example shows the use of the above-explained approach.


Output
Array 1 is multidimensional: No
Array 2 is multidimensional: Yes

Using a Recursive Function

This method involves writing a function that calls itself to traverse the array and check for nested arrays.

Example: In this example, the isMultidimensional function iterates through each element of the given array. If any element is itself an array (checked using is_array), the function returns true, indicating that the array is multidimensional. If no sub-array is found, the function returns false, indicating that the array is single-dimensional.


Output
Array 1 is single-dimensional
Array 2 is multidimensional

Using json_encode() and json_decode() Functions:

This method leverages the json_encode() function to convert the array to a JSON string and then uses json_decode() to decode it back. If the decoded array is an object, the original array is multidimensional.

Example


Output
Array 1 is single-dimensional
Array 2 is single-dimensional


Comment