Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How get only selected keys of an array using PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 331
    Comment on it

    Hello Reader's, If you having a multidimensional array from which you only want a single key values column then this blog is helpful to you.

    Let consider a array with full of key values:- 

    $exArray=array(
                array('name' => 'Ankit', 'coutry' => 'India'),
                array('name' => 'John', 'coutry' => 'Austria'),
                array('name' => 'Mack', 'coutry' => 'USA')
                );
    

    Now as per your condition you only want the column 'country' . So we'll use a loop function, this loop will run till the last key of the given array is traversed. Here you just have to take out the column having name country. Once you gettting the selected column put them in a new array. The array will be created dynamic so put "[]" brackets after it. In this brackets the key will be autu increamented. Lets see the code and logic of it.

    1 By using a own custom function:- 

    foreach ($exArray $getCountry) {
      $newArray[] = $getCountry['country'];
    }

    In the code above the only country is selecting in new array $newArray. And the output of this array will go like this:-

    array =>
    [0] => 'India'
    [1] => 'Austria'
    [2] => 'USA'

     But for the developers who are using PHP 5.5 or greated version. PHP itself having the this facility and it's name is array_column. This is an inbuilt function for PHP which uses two PARAM, given array  and key name. To use this function you have to create new array in which result will be get. Now set it to array_column() and first pass your array then the key. It will auto traverse and take out the making keys.

    It's code will be go like this:- 

    $names = array_column($samples, 'name');
    print_r($names);

    And the output it will be same like below:-

    array =>
    [0] => 'India'
    [1] => 'Austria'
    [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: