PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites

28 Jun 2016

PHP get particular key value from multidimensional array

You can get specific key from multidimensional array using any one of the below methods:

  1. Get Specific key value form multidimensional array using array_column:


     The array_column() returns the values from a single column in the input array. It works only from PHP version 5.5. You've a multidimentional array with details of user name and country. You tried to get the name of every array from multidimentional array. Consider the following exampale:

  <?php

    $array = array(
      0 => array(
        'name' => 'Guru',
        'country' => 'India'
      ),
      1 => array(
        'name' => 'Clark',
        'country' => 'USA'
      ),
      2 => array(
        'name' => 'Smith',
        'country' => 'United Kingdom'
      ),
      3 => array(
        'name' => 'John',
        'country' => 'USA'
      ),
    );

    $namesArray = array_column($array, 'name');
    print_r($namesArray);exit;

    When you run this program in the browser, you will get the output like below one:

    Array ( [0] => Guru [1] => Clark [2] => Smith [3] => John )

    For more details about array_coulmn, visit http://php.net/manual/en/function.array-column.php.

  2. Get Specific key value form multidimensional array using array_map:


    The array_map() applies the callback to the elements of the given arrays. It works from PHP version 4.0.6. The array_map() is alternate of array_column() in PHP

  <?php
    $namesArray = array_map(function($arr){
        return $arr['name'];
      }, $array);
    print_r($namesArray);exit;

    It will give same output as array_column. For more details about array_map, visit http://php.net/manual/en/function.array-map.php.

  3. Get Specific key value form multidimensional array using foreach loop:


  <?php
  $namesArray = array();
  foreach($array as $key => $val) {
    $namesArray[] =  $val['name'];
  }
  print_r($namesArray);exit;

  It will also give sample output as array_coulmn & array_map.

  Now I've hope you know how to get particular key value from multidimensional array in PHP.

Releated Articles: