How to Get Common Values from Two Different Arrays in PHP

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



Leave a reply



Submit