6

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 ?

0

2 Answers 2

13

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']

}
Sign up to request clarification or add additional context in comments.

1 Comment

Damn ! I was doing the same but INSIDE the second foreach loop, so I was getting the first char of each entry only: MMDD . Now I got it, thanks.
0

Surname also a key in that array so you need to print like as below

foreach($charsarray as $key => $val){
   echo $val['surname'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.