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
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
Contact Us