Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to get particular column of a multidimensional array using foreach loop in PHP?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 438
    Comment on it


    Hi Reader's,
    Welcome to FindNerd, today we are going to discuss how to get particular column of a multidimensional array using foreach loop in PHP?

    Let have an  array with full of key values:-

    $detailArr=array(
    array('name' => 'Ravi', 'coutry' => 'India'),
    array('name' => 'Mac', 'coutry' => 'Canada'),
    array('name' => 'Joy', 'coutry' => 'USA')
    );

    Suppose you  have a multidimensional array and you only want a single key values column,then you should use loop function,this loop will run till the last key of the given array is traversed.

    You just want to take out the column having name country. The array will be created dynamic so put [] brackets after it. In this brackets the key will be auto incremented.

    you can see below code for better understanding

     

    foreach ($detailArr as $CountryNmae) {
        $CountryDetail[] = $CountryNmae['country'];
    }
    
    

    So final code will look like this

    <?php
      //define a array
      $detailArr=array(
      array('name' => 'Ravi', 'country' => 'India'),
      array('name' => 'Mac', 'country' => 'Canada'),
      array('name' => 'Joy', 'country' => 'USA')
      );
    
      //start loop
      foreach ($detailArr as $CountryNmae) {
          $CountryDetail[] = $CountryNmae['country'];
      }
         //print output
         echo "<pre>";print_r($CountryDetail);die;
    
    ?>

    Output will come following:

    
    Array
    (
        [0] => India
        [1] => Canada
        [2] => USA
    )

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: