Backend Development 4 min read

Using PHP's array_diff() Function to Compute Array Differences

This article explains how PHP's array_diff() function works, detailing its syntax, parameters, return value, and providing three practical code examples that demonstrate computing array differences for indexed and associative arrays in various.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's array_diff() Function to Compute Array Differences

In PHP, the array_diff() function is a useful tool for computing the difference between arrays. It takes two or more arrays and returns a new array containing the values from the first array that are not present in any of the other arrays.

Syntax

<code>array_diff(array1, array2, array3, ...)</code>

Parameters

array1 : The first array to compare (required).

array2 : The second array to compare (required).

array3, ... : Additional arrays to compare (optional).

Return Value

Returns a new array containing the values from array1 that are not present in any of the other arrays.

Examples

Example 1

<code>$array1 = array("apple", "banana", "orange", "grape");
$array2 = array("banana", "grape", "pear");
$result = array_diff($array1, $array2);
print_r($result);
</code>

Output:

<code>Array
(
    [0] => apple
    [2] => orange
)
</code>

This shows that "apple" and "orange" are not found in $array2 .

Example 2

<code>$array1 = array(1, 2, 3, 4, 5);
$array2 = array(2, 3, 6);
$result = array_diff($array1, $array2);
print_r($result);
</code>

Output:

<code>Array
(
    [0] => 1
    [3] => 4
    [4] => 5
)
</code>

Values 1, 4, and 5 are not present in $array2 .

Example 3

<code>$array1 = array("a" => "apple", "b" => "banana", "c" => "orange");
$array2 = array("a" => "apple", "b" => "pear");
$result = array_diff($array1, $array2);
print_r($result);
</code>

Output:

<code>Array
(
    [c] => orange
)
</code>

The element with key "c" ("orange") does not exist in $array2 .

Summary

The array_diff() function is a practical PHP function for calculating array differences. By comparing multiple arrays, you can identify elements that are unique to the first array.

BackendProgrammingPHPcode examplesarray_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.