PHP Print Two or More Dimensional Value



Two or more dimensional array is another type of array where more than one arrays are linked with each other. Mainly an array is a collection of multiple values. Every index of an array stores specific value. When an index of an array stores another array then it becomes a multidimensional array. This multidimensional value can be print easily by foreach loop, for or while. There is an array is given below. This needs to be printed. For printing two-dimensional array let's notice on below code


<?php

    $a = array(
      4,5,11,25,76,23,7,array(56,90,34,21)
    );
    foreach ($a as  $value) {
      if (is_array($value)) {
        foreach ($value as $v1) {
          echo $v1." ";
        }
      }else{
        echo $value." ";
      }
      echo "
"; } ?>

Printed values are


4 
5 
11 
25 
76 
23 
7 
56 90 34 21

Here a is variable with array values stored in different indexes. For this reason, foreach loop is used for printing array values. Its last index is also an array. All have been printed simply. As the last index is an array so we have checked every time that printed value is an array or not. For this reason, is_array() function is used. This is_array() function returns true if values becomes an array. For printing last index(array) we used foreach loop again. Here nested for loop has been used for printing values.   For printing associative values the same process is followed.