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 ?
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']
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With