0

Would love someone's help please - learning PHP, my first language.

I can loop through a single array using foreach, but what if I want to get at 2 arrays? This is my example using darts players!

$nationality = array ('Green' => 'England', 'Dekker' => 'Holland','Bunting'=> 'England', 'Montgomery'=>'Scotland');

$ranking = array ('Green' => 4, 'Dekker' => 6,'Bunting'=> 1, 'Montgomery'=> 57);

Q: How do I utilise foreach to loop through both arrays and generate a sentence such as (array data in bold)"Green is from England and is ranked 4."

2
  • You could post some code you have already, so we can tweak it. Welcome on SO! Commented Jan 14, 2014 at 12:12
  • Thank you so much @Prisoner! You put me on the path to working out how to do it with a multidimensional array too. Commented Jan 14, 2014 at 12:37

1 Answer 1

2
$nationality = array ('Green' => 'England', 'Dekker' => 'Holland','Bunting'=> 'England', 'Montgomery'=>'Scotland');

$ranking = array ('Green' => 4, 'Dekker' => 6,'Bunting'=> 1, 'Montgomery'=> 57);

foreach($nationality as $player => $country){
    echo "{$player} is from {$country} and is ranked {$ranking[$player]}. ";
}

This will output:

Green is from England and is ranked 4. Dekker is from Holland and is ranked 6. Bunting is from England and is ranked 1. Montgomery is from Scotland and is ranked 57.

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

4 Comments

To clarify: He uses the current "$player" as index for the "$ranking". So both arrays use the same index which prints the correct output.
Thanks @Y U NO WORK, are you saying it could also be done using a different index for $ranking?
@simien, you could also look through $ranking instead of $nationality, as the keys for the data are the same.
I assumed there had to be a common key for this foreach to use both arrays? What if, say, $ranking had a different key?

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.