Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, getting $value out of a specific $key in associative multidimensional array

I'm quite new with PHP and I'm facing a problem with arrays. say I have a multidimensional associative array called $charsarray like this:

[1] => ([name] => mickey [surname] => mouse)
[2] => ([name] => donald [surname] => duck)
...
[N] => (...)

I need to extract the "surname" field of each entry so my code has nested foreach:

foreach($charsarray as $key => $value )
{
    foreach($value => $singlechar)
    {
      echo $singlechar
    }
}

This outputs both mickey mouse donald duck since these are the values of the associative array.

If I want to extract only surnames I could write an if statement to check against the key surname.

Is there a better approach to this without using the if statement ?

like image 613
Podarce Avatar asked May 17 '18 13:05

Podarce


1 Answers

You don't need to loop through the entire thing. You can just reference the specific value in the array by using correct index (surname).

foreach($charsarray as $key => $value )
{
   echo $value['surname']

}
like image 69
bassxzero Avatar answered Nov 05 '22 10:11

bassxzero