PHP, How To Compare Two Arrays And Get Values That Are Not Present In Second Array
In this tutorial, we will show you how to use the array_diff()
function in PHP to compare two arrays and find values that are not present in the second array. With our step-by-step guide on PHP Compare Two Arrays, you can easily enhance your programming skills and improve your efficiency in array manipulation. By learning how to compare arrays in PHP, you can simplify your code and perform more complex tasks with ease.
You can compare two arrays in PHP using the array_diff()
function, which returns an array containing all the values from the first array that are not present in any of the other arrays.
Here’s an example code snippet:
1 2 3 4 5 6 |
$array1 = array('apple', 'banana', 'orange', 'grape'); $array2 = array('banana', 'orange', 'kiwi'); $not_in_array2 = array_diff($array1, $array2); print_r($not_in_array2); |
Output:
1 2 3 4 5 |
Array ( [0] => apple [3] => grape ) |
In this example, $array1
and $array2
are the two arrays that we want to compare. The array_diff()
function takes these two arrays as arguments, with $array1
as the first argument and $array2
as the second argument.
The output of the array_diff()
function is an array containing all the values from $array1
that are not present in $array2
. In this case, the output is an array containing ‘apple’ and ‘grape’, because these values are not present in $array2
.
You can then use the resulting array $not_in_array2
for further processing, such as displaying the values or storing them in another array.
Related Links:
- Official PHP documentation for
array_diff()
function – https://www.php.net/manual/en/function.array-diff.php - PHP tutorial on comparing arrays – https://www.w3schools.com/php/php_arrays_compare.asp
- Example of array comparison in PHP – https://www.geeksforgeeks.org/php-array_diff-function/
- StackOverflow discussion on array comparison in PHP – https://stackoverflow.com/questions/11857937/php-comparing-two-arrays-and-returning-the-differences
These links can provide more in-depth information and resources related to comparing arrays in PHP.