[php] How to get single value from this multi-dimensional PHP array

Example print_r($myarray)

Array
(
    [0] => Array
    (
        [id] => 6578765
        [name] => John Smith
        [first_name] => John
        [last_name] => Smith
        [link] => http://www.example.com
        [gender] => male
        [email] => [email protected]
        [timezone] => 8
        [updated_time] => 2010-12-07T21:02:21+0000
    )
)

Question, how to get the $myarray in single value like:

echo $myarray['email'];  will show [email protected]

This question is related to php arrays

The answer is


echo $myarray[0]->['email'];

Try this only if it you are passing the stdclass object


The first element of $myarray is the array of values you want. So, right now,

echo $myarray[0]['email']; // This outputs '[email protected]'

If you want that array to become $myarray, then you just have to do

$myarray = $myarray[0];

Now, $myarray['email'] etc. will output as expected.


I think you want this:

foreach ($myarray as $key => $value) {
    echo "$key = $value\n";
}

Use array_shift function

$myarray = array_shift($myarray);

This will move array elements one level up and you can access any array element without using [0] key

echo $myarray['email'];  

will show [email protected]


You can also use array_column(). It's available from PHP 5.5: php.net/manual/en/function.array-column.php

It returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.

print_r(array_column($myarray, 'email'));