Jump to: navigation, search

Php array diff

From w3cyberlearnings

Contents

PHP function array_diff

This function compares two or more arrays. By using the first array to compare with all other arrays, and it will return the array element from the first array that is not present in other arrays.

Syntax array_diff

  • array1: array to be used for the comparison
  • array2: second array
  • array3: third array
array_diff(array1, array2, array3);

Example 1

<?php

$person1 = array('bob', 'nank', 'lony', 'king');
$person2 = array('mark', 'bob', 'john', 'smit');
$person3 = array('king', 'lory', 'many', 'jammy');

$person_diff = array_diff($person1, $person2, $person3);
print_r($person_diff);
?>


Output

Array ( [1] => nank [2] => lony )

Example 2

<?php

$president1 = array('obama', 'george bush', 'bill clinton');
$president2 = array('omaha', 'obama', 'bill clinton');

$president_diff = array_diff($president1, $president2);
print_r($president_diff);
?>

Output

Array ( [1] => george bush )

Example 3

<?php

$cambodia_fruit = array('mango', 'coconut', 'black-spring','orange','plam fruit');
$us_fruit = array('mango', 'banana', 'orange', 'apple','coconut');

$fruits_diff = array_diff($cambodia_fruit, $us_fruit);

foreach ($fruits_diff as $fruits) {
	echo "{$fruits} is Cambodia national fruit!<br/>";
}
?>

Output

black-spring is Cambodia national fruit!
plam fruit is Cambodia national fruit!

Related Links


Navigation
Web
SQL
MISC
References