Backend Development 4 min read

Using PHP array_diff() to Compare Arrays

This article explains how the PHP function array_diff() works for comparing indexed and associative arrays, provides clear code examples, and highlights its behavior of returning values present only in the first array while ignoring keys during comparison.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP array_diff() to Compare Arrays

In PHP development, array manipulation and comparison are common tasks, and PHP offers many convenient functions for these operations. One frequently used function is array_diff() , which helps compare the differences between arrays.

The array_diff() function removes values from the first array that appear in any of the subsequent arrays and returns a new array containing the remaining values. It accepts multiple arrays as arguments.

Below is a concrete code example:

<?php
$array1 = array("apple", "banana", "orange", "pear");
$array2 = array("apple", "banana", "grape");
$array3 = array("orange", "pear", "grapefruit");

$result = array_diff($array1, $array2, $array3);

print_r($result);
?>

The script defines three arrays ($array1, $array2, $array3), passes them to array_diff() , and prints the result. The output shows a new array containing the values “orange” and “pear”, which are present in $array1 but not in $array2 or $array3.

Note that array_diff() only returns values that exist in the first array and are absent from all other arrays; any value that appears in another array is excluded from the result.

Additionally, array_diff() can be used with associative arrays. It ignores the keys and compares only the values. The following example demonstrates this behavior:

<?php
$array1 = array("apple" => 1, "banana" => 2, "orange" => 3, "pear" => 4);
$array2 = array("apple" => 1, "banana" => 2, "grape" => 3);
$array3 = array("orange" => 1, "pear" => 2, "grapefruit" => 3);

$result = array_diff($array1, $array2, $array3);

print_r($result);
?>

Running the code yields an array where the keys “orange” and “pear” remain, showing that when keys are identical, array_diff() compares the values and returns the differing ones.

In summary, array_diff() is a highly useful PHP function for comparing arrays, capable of handling multiple arrays and both indexed and associative arrays, which can simplify data processing and improve development efficiency.

BackendPHPArray Comparisonphp-functionsarray_diff
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.