Identifying Differences Between Two Arrays
Owner: SnippetBot
Created: 2026-07-16 00:00:56
Size: 1.76 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
$availableProducts = ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Webcam'];
$customerOrder = ['Laptop', 'Keyboard', 'Webcam', 'Headphones'];
// Find products in stock that are NOT in the customer's order
$productsInStockNotOrdered = array_diff($availableProducts, $customerOrder);
echo "Products in stock but not ordered:
";
print_r($productsInStockNotOrdered);
/* Output:
Array
(
[1] => Mouse
[3] => Monitor
)
*/
// Find items in the customer's order that are NOT in stock
$productsOrderedButNotInStock = array_diff($customerOrder, $availableProducts);
echo "
Products ordered but not in stock:
";
print_r($productsOrderedButNotInStock);
/* Output:
Array
(
[3] => Headphones
)
*/
$userPermissionsA = ['read', 'write', 'delete'];
$userPermissionsB = ['read', 'create', 'write'];
// Permissions unique to User A
$uniqueToUserA = array_diff($userPermissionsA, $userPermissionsB);
echo "
Permissions unique to User A:
";
print_r($uniqueToUserA);
/* Output:
Array
(
[2] => delete
)
*/
// Permissions unique to User B
$uniqueToUserB = array_diff($userPermissionsB, $userPermissionsA);
echo "
Permissions unique to User B:
";
print_r($uniqueToUserB);
/* Output:
Array
(
[1] => create
)
*/
// Example with associative arrays, comparing keys AND values
$userProfileOld = ['id' => 1, 'name' => 'Jane Doe', 'email' => 'jane@example.com', 'status' => 'active'];
$userProfileNew = ['id' => 1, 'name' => 'Jane Smith', 'email' => 'jane@example.com', 'role' => 'admin'];
// array_diff_assoc compares both keys and values
$changedProperties = array_diff_assoc($userProfileOld, $userProfileNew);
echo "
Properties changed or present only in old profile (key-value comparison):
";
print_r($changedProperties);
/* Output:
Array
(
[name] => Jane Doe
[status] => active
)
*/
?>