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

PhpArrays

Php Problem Overview


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@domain.com
        [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]

Php Solutions


Solution 1 - Php

Look at the keys and indentation in your print_r:

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

echo $myarray[0]['gender'];

...etc

Solution 2 - Php

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]

Solution 3 - Php

I think you want this:

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

Solution 4 - Php

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'));

Solution 5 - Php

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

Try this only if it you are passing the stdclass object

Solution 6 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwowView Question on Stackoverflow
Solution 1 - PhpDan GrossmanView Answer on Stackoverflow
Solution 2 - PhpVirendra YadavView Answer on Stackoverflow
Solution 3 - PhpMike AxiakView Answer on Stackoverflow
Solution 4 - PhpFrancesco CasulaView Answer on Stackoverflow
Solution 5 - PhpMasad AshrafView Answer on Stackoverflow
Solution 6 - Phpv64View Answer on Stackoverflow