Jump to: navigation, search

Php array intersect

From w3cyberlearnings

Contents

PHP function array_intersect

This function compares two or more array. It returns an array key and value pairs from the first array that each of its elements existed in other arrays.

Syntax array_intersect

  • array1: array one for comparison
  • array2: second array
  • array3: third array
array_intersect(array1, array2, array3,...);

Example 1

<?php

$score1 = array(40, 53, 43, 23);
$score2 = array(53, 40, 42, 43);
$score3 = array(34, 53, 43, 32);

$score_intersect = array_intersect($score1, $score2, $score3);
print_r($score_intersect);
?>


Output

  • 53 and 43 existed in $score2 and $score3, the array order is not important.

Array
(
    [1] => 53
    [2] => 43
)


Example 2

<?php

$winers1 = array('john','mark','marry','christ');
$winers2 = array('mark','christ','blair','jocob');
$winers3 = array('jocob','mark','marry','christ');
$winner4 = array('christ','marry','mark','jocob');

$winers = array_intersect($winers1, $winers2, $winers3, $winner4);

foreach($winers as $winner) {
	echo "{$winner} won in all games.<br/>";
}
?>

Output

mark won in all games.
christ won in all games.

Related Links


Navigation
Web
SQL
MISC
References