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

array_diff(array1, array2, array3, ...)

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

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

Output:

Array
(
    [0] => apple
    [2] => orange
)

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

Example 2

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

Output:

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

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

Example 3

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

Output:

Array
(
    [c] => orange
)

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPCode 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

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.