0

I have two arrays:

$anna_array = array("soccer" => "10", "basketball" => "20", "tennis" => "30", "atletics" => "40", "volleyball" => "50");
$john_array = array("soccer" => "15", "basketball" => "15", "atletics" => "45");

Explanation

The score of Anna at Soccer is 10 and of John is 15 and so on.

I want to return the same activities in both arrays. Something like:

Anna activities: Soccer = 10 - Basketball = 20 - Atletics = 40.

John activities: Soccer = 15 - Basketball = 15 - Atletics = 45.

Can anyone help me with this?

3
  • 1
    I appreciate that you added a clear question, but it's too broad, because you didn't include any attempt. For the first problem: iterate through the first array and for every element from the first array iterate through the second array. If you find an element that is in both arrays, you can add it to a third array and that would be the final result. Then you can use the first part and you can place your code inside the second loop. You can keep 2 variables a for Anna, and j for John that are 0 and during the comparison (inside the if block) you can increment a or j. Commented Jan 23, 2016 at 19:57
  • @Fredrico. No, it is an idea I want to use on my website to help my students to work harder. Commented Jan 23, 2016 at 20:00
  • @engineer Thank you for the explanation. I will try to solve the first problem then the second. I really need this for my students. Commented Jan 23, 2016 at 20:07

1 Answer 1

1

You can compute the intersection of an array with array_intersect_key.

$anna_array = array('Soccer' => "10", 'Basketball' => "20", 'Tennis' => "30", 'Atletics' => "40", 'Volleyball' => "50");
$john_array = array('Soccer' => "15", 'Basketball' => "15", 'Atletics' => "45");

$anna_activities = array_intersect_key($anna_array, $john_array);
$john_activities = array_intersect_key($john_array, $anna_array);

Demo.

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

1 Comment

Thank you very much Federico. Now to the second problem:)

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.