How to get common values from two different arrays in PHP
Native PHP functions are faster than trying to build your own algorithm.
$result = array_intersect($array1, $array2);
Find common values in multiple arrays with PHP
array_intersect()
$intersect = array_intersect($array1,$array2,$array3);
If you don't know how many arrays you have, then build up an array of arrays and user call_user_func_array()
$list = array();
$list[] = $array1;
$list[] = $array2;
$list[] = $array3;
$intersect = call_user_func_array('array_intersect',$list);
Find common value within two array in php
Use
array_unique(array_merge(['Ava', 'Emma', 'Olivia'], ['Olivia', 'Sophia', 'Emma']));
array_merge
will put all values in a single array then array_unique
wil remove duplicates.
How to get the same value from two arrays in PHP?
<?php
$arr = array_intersect(array('a', 'b', 'c', 'd'),
array('c', 'd', 'e', 'f'));
print_r(array_values($arr));
Finding common elements in multiple arrays php
array_intersect()
$intersect = array_intersect($array1,$array2,$array3);
If you don't know how many arrays you have, then build up an array of arrays and user call_user_func_array()
$list = array();
$list[] = $array1;
$list[] = $array2;
$list[] = $array3;
$intersect = call_user_func_array('array_intersect',$list);
Reference Here
Comparing 2 arrays in PHP and get the common values to a different array
You need to use array_intersect()
$finalArray = array_intersect($arr1,$arr2);
print_r($finalArray);
Output: https://3v4l.org/53mDL
Get uncommon values from two or more arrays
Use array_diff
and array_merge
:
$result = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));
Here's a demo.
For multiple arrays, combine it with a callback and array_reduce
:
function unique(&$a, $b) {
return $a ? array_merge(array_diff($a, $b), array_diff($b, $a)) : $b;
}
$arrays = array(
array('green', 'red', 'blue'),
array('green', 'yellow', 'red')
);
$result = array_reduce($arrays, 'unique');
And here's a demo of that.
Related Topics
Custom Laravel Validation Messages
How to Handle $_Post Data in MVC
Setcookie() Does Not Set Cookie in Google Chrome
Which Is Faster and Better, Switch Case or If Else If
Uploading a File in Chunks Using HTML5
Access Denied for User 'Root'@'Localhost' with PHPmyadmin
Convert Utc Dates to Local Time in PHP
How to Get the Unicode Value of a Character or Vise Versa with PHP
How to Get Previous Month and Year Relative to Today, Using Strtotime and Date
How to Make PHP Generate Chunked Response
Curl Code in PHP Dumps Output to the Page
PHP - Indirect Modification of Overloaded Property
Many Hash Iterations: Append Salt Every Time
Query_Posts() Should Be Avoided
Pdostatement (Mysql): Inserting Value 0 into a Bit(1) Field Results in 1 Written in Table