Jump to: navigation, search

Php array diff assoc

From w3cyberlearnings

Contents

PHP function array_diff_assoc

This function compares two or more arrays, and return a new array from the first array when the element from the first array does not match with elements in other arrays. The first element in the first array compares with the first element in the second array or third array.

Syntax array_diff_assoc

  • array1: first array that use other arrays compare with
  • array2: second array
  • array3: third array
  • array...
array_diff_assoc(array1, array2, array3...);

Example 1

<?php

$country1 = array('China', 'Cambodia', 'Malaysia');
$country2 = array('Malaysia', 'Vietnam', 'Malaysia');

$country_diff = array_diff_assoc($country1, $country2);
print_r($country_diff);
?>

Output

  • China and Cambodia are not contained in the second array.
Array ( [0] => China [1] => Cambodia )

Example 2: use associative array

<?php

$country1 = array('China'=>39, 'Cambodia'=>3, 'Malaysia'=>40);
$country2 = array('Malaysia'=>33, 'Vietnam', 'Malaysia'=>40);

$country_diff = array_diff_assoc($country1, $country2);
print_r($country_diff);
?>

Output

Array ( [China] => 39 [Cambodia] => 3 )

Example 3

<?php

$country1 = array('China' => 39, 'Cambodia' => 3, 'Malaysia' => 40);
$country2 = array('Malaysia' => 33, 'Vietnam', 'Malaysia' => 40);

$country_diff = array_diff_assoc($country1, $country2);
foreach ($country_diff as $country => $score) {
	echo "{$country} does not play in the second turn, however it score {$score} in the first play<br/>";
}
?>

Output

China does not play in the second turn, however it score 39 in the first play
Cambodia does not play in the second turn, however it score 3 in the first play

Related Links


Navigation
Web
SQL
MISC
References