I am new in PHP and now i'm facing a problem with arrays. I have two sets of arrays.I want to form a result array which contains all the mismatched elements in both the array.
eg:
array1=Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
array2=Array ( [0] => 1 [1] => 2 [2]=>9)
result array what i'm expecting should be
result array=Array([0] => 3 [1] => 4 [2] => 5 [3] => 9 )
Use array_diff and array_merge
$array1 = [1,2,3,4,5];
$array2 = [1,2,9];
$diff1 = array_diff($array1, $array2); //Find difference element in 1st array
$diff2 = array_diff($array2, $array1); //Find difference element in 2nd array
print_r(array_merge($diff1, $diff2)); // Merge the results
Result:
Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 9
)
In one line:
print_r(array_merge(array_diff($array1,$array2),array_diff($array2,$array1));
Update 1 : From the comments
It is because, your array values has spaces . Just trim out:
Use
$array1 = array_map("trim", $prev_array);
$array2 = array_map("trim", $checked_array);
Instead of:
$array1 = $prev_array;
$array2 = $checked_array;
Get elements from both arrays that are not present in the other. Then merges the results.
array_merge(array_diff($array1, $array2), array_diff($array2, $array1))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.