Foreach in php multidimensional array.

Array always has been a  solution for solving a simple to complex logical problems.  As far as my programming experience is concerned array has been the integral part to manipulate, solve most of the logical problems.  In php there are 3 different kinds of array i.e Indexed array , associative array and multidimensional array . Basically we use loop or do iteration on indexed array and associative array , but here I will go with the technique of using ‘foreach’ iteration on multidimensional array .

Lets suppose I have multidimensional array as follows:

$arr =  array ('Information'=>array('name'=> 'Ram Prasad',
                                    'height'=>'6feet',
                                    'address'=>' Nepal ',
                                    'gender'=>' Not Avaliable' ));

IMPLIES

Array
(
    [Information] => Array
        (
            [name] => Ram Prasad
            [height] => 6feet
            [address] =>  Nepal
            [gender] =>  Not Avaliable
        )
 
)

Now we can extract the data from the above array using php “foreach” keyword in the following way.

foreach($arr as $key =>$value)
 {
       if (is_array($value) and count($value))
      {
           echo "ArrayName = ". $key ."<br>";
           foreach($value as $key2=> $value2)
           {
               echo $key2 ."  =   ". $value2 ."<br>" ;
           }
      }
 }

This will print as follows on the browser.

ArrayName = Information
name = Ram Prasad
height = 6feet
address = Nepal
gender = Not Avaliable

I hope this can help getting the data from the php  multidimensional array using foreach .

856 views
Php

Comments

One Response to “Foreach in php multidimensional array.”

Leave Comment

(required)

(required)