PHP

Find Differences and Intersections Between PHP Arrays

Discover how to compare two or more PHP arrays to find elements unique to one array (`array_diff`) or common to all (`array_intersect`).

<?php
$array1 = ['apple', 'banana', 'orange', 'grape'];
$array2 = ['banana', 'kiwi', 'apple', 'mango'];
$array3 = ['apple', 'grape', 'lemon'];

// Elements in array1 that are not in array2
$difference1 = array_diff($array1, $array2);
// $difference1 will be ['orange', 'grape']

// Elements in array2 that are not in array1
$difference2 = array_diff($array2, $array1);
// $difference2 will be ['kiwi', 'mango']

// Elements common to all arrays
$intersection = array_intersect($array1, $array2, $array3);
// $intersection will be ['apple']

// For associative arrays, use _assoc versions for key comparison as well
$userRoles1 = ['user1' => 'admin', 'user2' => 'editor', 'user3' => 'viewer'];
$userRoles2 = ['user2' => 'editor', 'user4' => 'guest', 'user1' => 'admin'];

// Values that are in $userRoles1 but not in $userRoles2 (values only)
$diffValues = array_diff($userRoles1, $userRoles2);
// $diffValues will be ['user3' => 'viewer']

// Entries (key-value pairs) that are in $userRoles1 but not in $userRoles2
$diffAssoc = array_diff_assoc($userRoles1, $userRoles2);
// $diffAssoc will be ['user3' => 'viewer'] because ('user1' => 'admin') and ('user2' => 'editor') match both key and value
?>
How it works: PHP offers functions to compare arrays based on their values. `array_diff()` returns values present in the first array but not in any subsequent arrays, ignoring keys. `array_intersect()` returns values present in all provided arrays. For associative arrays, `array_diff_assoc()` and `array_intersect_assoc()` also compare keys, ensuring a stricter match for identical key-value pairs.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs