Jump to: navigation, search

Php array intersect key

From w3cyberlearnings

Contents

PHP function array_intersect_key

This function compares two or more arrays use the first array key for the comparison. If the key existed in all other arrays, it will return the key and value pairs from the first array.

Syntax array_intersect_key

  • array1: array1 for comparison with all other arrays
  • array2: second array
  • array3: third array
array_intersect_key(array1, array2, array3,...);

Example 1

<?php

$student1 = array('Abbey' => 89, 'Abbie' => 88, 'Abbigail' => 83, 'Aiyana' => 93);
$student2 = array('Abbey' => 81, 'Abbie' => 89, 'Aimee' => 84, 'Aiyana' => 92);
$student3 = array('Abbey' => 90, 'Abbie' => 87, 'Abbigail' => 87, 'Aiyana' => 88);

$student_list = array_intersect_key($student1, $student2, $student3);
foreach ($student_list as $name => $score) {
	echo "{$name} takes all the exams, and the first exam scores {$score}.<br/>";
}
?>

Output


Abbey takes all the exams, and the first exam scores 89.
Abbie takes all the exams, and the first exam scores 88.
Aiyana takes all the exams, and the first exam scores 93.

Example 2

<?php

$score_players1 = array(50 => 'Alexandra', 43 => 'Eileen', 53 => 'Katrina', 65 => 'Alondra');
$score_players2 = array(43 => 'Alondra', 50 => 'Elisabeth', 54 => 'Katelynn', 83 => 'Allyssa');
$score_players3 = array(50 => 'Diamond', 90 => 'Allison', 79 => 'Alicia', 77 => 'Aliyah');

$scores = array_intersect_key($score_players1, $score_players2, $score_players3);

foreach($scores as $score=>$name) {
	echo "Score {$score} happens in all games, and the first players received the score is {$name}<br/>";
}
?>

Output

Score 50 happens in all games, and the first players received the score is Alexandra

Related Links


Navigation
Web
SQL
MISC
References