Jump to: navigation, search

Php array diff uassoc

From w3cyberlearnings

Contents

PHP function array_diff_uassoc

This function compares two or more arrays index based on the first array. Before doing the comparison, this function calls the user-defined callback function to check each array and it returns according to the user-defined function.

Syntax array_diff_uassoc

  • array1: first array to use for the comparison with all other arrays
  • array2: second array
  • array3: third array
  • callback: check and return from the user-defined function
array_diff_uassoc(array1, array2, array3, ...,callback);

Note

Do not use duplicate array keys, please see the example.

Example 1

<?php

// call back function to compare two score
function check_score($vscore1, $vscore2) {
	if ($vscore1 == $vscore2) {
		return 0;
	} else if ($vscore1 > $vscore2) {
		return 1;
	} else {
		return -1;
	}
}

$check_score = array_diff_uassoc(
          array(4 => 'mark', 3 => 'john', 2 => 'jake'), 
          array(4 => 'mark', 3 => 'john', 12 => 'jake'), "check_score");

print_r($check_score);
?>

Output

Array ( [2] => jake )

Example 2

  • This example do not display the result correctly, due to the confuse in the array key.

As you can see, the second array contains array key=53' twice.

  • In this condition, you may use another method to compare score for each array key
<?php

// call back function to compare two score
function check_score($vscore1, $vscore2) {
	if ($vscore1 == $vscore2) {
		return 0;
	}
	else if ($vscore1 > $vscore2) {
		return 1;
	} else {
		return -1;
	}
}

$score1 = array(50 => 'Bob', 53 => 'Janny', 41 => 'Wood',40=>'Makr');
$score2 = array(13 => 'Bob', 53 => 'Janny', 53 => 'Wood',40=>'Makr');


$check_score = array_diff_uassoc($score1, $score2, "check_score");

print_r($check_score);
?>

Output

Array
(
    [50] => Bob
    [53] => Janny
    [41] => Wood
)
</body>

Example 3

<?php

// call back function to compare two score
function callback($vscore1, $vscore2) {
	if ($vscore1 == $vscore2) {
		return 0;
	} else if ($vscore1 > $vscore2) {
		return 1;
	} else {
		return -1;
	}
}

$country1 = array('c' => 'cambodia', 'ch' => 'china', 'us' => 'USA');
$country2 = array('c' => 'china', 'ch' => 'chichno', 'us' => 'United States');
$country2 = array('c' => 'chile', 'ch' => 'china', 'us' => 'United States');

$check_score = array_diff_uassoc($country1, $country2, "callback");

print_r($check_score);
?>


Output

Array
(
    [c] => cambodia
    [us] => USA
)

Related Links


Navigation
Web
SQL
MISC
References