How to use Nested foreach Loop In PHP

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.

PHP
<?php

function is_multidimensional(array $array) {
    foreach ($array as $value) {
        if (is_array($value)) {
            return true;
        }
    }
    return false;
}

$array1 = [1, 2, 3];
$array2 = [[1, 2], [3, 4]];

echo "Array 1 is multidimensional: " . (is_multidimensional($array1) ? "Yes" : "No") . "\n";
echo "Array 2 is multidimensional: " . (is_multidimensional($array2) ? "Yes" : "No") . "\n";

?>

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


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

Given an array (single-dimensional or multi-dimensional) and 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:

Table of Content

  • Using rsort() function
  • Using Nested foreach Loop

Similar Reads

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....

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....

Contact Us