In daily PHP development, we often encounter situations where the results returned by the array processing function do not match expectations. At this time, if you can cleverly combine the two functions of var_dump() and array_diff() , you can understand the data changes before and after the function is executed, thereby positioning the problem more quickly.
This article will use an example to demonstrate how to use these two functions to analyze the execution effect of PHP functions.
var_dump() : Used to output detailed information of a variable, including types and values, which are very suitable for debugging.
array_diff() : Returns an array containing values that appear in the first array but not in other arrays.
Suppose we get a set of user data from the interface and hope to clean up invalid users. We wrote a function filterInvalidUsers() , but the result doesn't seem right. At this time, we can use var_dump() and array_diff() to analyze the problem.
<?php
function filterInvalidUsers($users) {
return array_filter($users, function($user) {
return isset($user['email']) && filter_var($user['email'], FILTER_VALIDATE_EMAIL);
});
}
// Raw data
$originalUsers = [
['id' => 1, 'email' => 'user1@m66.net'],
['id' => 2, 'email' => 'invalid-email'],
['id' => 3], // Lack email
['id' => 4, 'email' => 'user4@m66.net'],
];
// Execute functions
$filteredUsers = filterInvalidUsers($originalUsers);
// use var_dump() Output result
echo "Filtered user list:\n";
var_dump($filteredUsers);
// use array_diff() See which users are filtered out
$diff = array_udiff($originalUsers, $filteredUsers, function($a, $b) {
return $a['id'] <=> $b['id'];
});
echo "\nThe filtered users have:\n";
var_dump($diff);
Through var_dump() , we can see that in the filtered user array, only users with legitimate mailbox format are left. array_udiff() (bringing callback function is used to compare array elements) can tell us which users are removed from the original array, so that developers can confirm whether the function behavior meets expectations.
If you only care about the changes in the array content, you can only compare the key values instead of the entire structure.
The array_diff() series functions are compared by strings by default. If it is a complex structure, it is recommended to use array_udiff() and pass in a custom comparison function.
Adding some prompt text when using var_dump() can make debugging information clearer.
Debugging is an indispensable part of the programming process, and var_dump() and array_diff() are two very powerful "microscopes". By reasonably combining these two tools, you can have a deeper understanding of the processing logic of functions, especially when dealing with complex arrays, helping you discover and solve problems faster. Hope this article will be helpful to you when debugging PHP programs!