Reputation:
Is there anyway to compare arrays in PHP using an in-built function, short of doing some sort of loop?
$a1 = array(1,2,3);
$a2 = array(1,2,3);
if (array_are_same($a1, $a2)) {
// code here
}
Btw, the array values will not always be in the same order.
Upvotes: 34
Views: 103458
Reputation: 101
I just wanted to contribute that:
echo var_export([1 => 2, 0 => 1, 3] == [1, 2, 3], 1);
Echoes true
. Therefore the ==
operator does not check that the elements in the array are in the same order, in the manner you would expect. Meaning array_values of the above are [2, 1, 3] and [1, 2, 3]. Yet because their keys have the same values, they are equal according to ==
operator.
(Remember [1, 2, 3] creates this array: [0 => 1, 1 => 2, 2 => 3])
Upvotes: 1
Reputation: 231
this is a simple way to get the difference:
$array1 = [40,10,30,20,50];
$array2 = [10,30];
$result = array_filter(
$array1,
function($var) use($array2){
if(in_array($var, $array2)){
return $var;
}
}
);
print_r($result); //Array ( [0] => 10 [1] => 30 )
Upvotes: 0
Reputation: 559
If you want to search some array inside a big array of arrays (>10k) then much more quickly is comparing serialized arrays (saved in cache). Example from work with URL:
/**
@return array
*/
function createCache()
{
$cache = [];
foreach ($this->listOfUrl() as $url => $args)
{
ksort($args);
$cache['url'][$url] = $args;
$cache['arr'][crc32(serialize($args))] = $url;
}
return $cache;
}
/**
@param array $args
@return string
*/
function searchUrl($args)
{
ksort($params);
$crc = crc32(serialize($params));
return isset($this->cache['arr'][$crc]) ? $this->cache['arr'][$crc] : NULL;
}
/**
@param string $url
@return array
*/
function searchArgs($url)
{
return isset($this->cache['url'][$url]) ? $this->cache['url'][$url] : NULL;
}
Upvotes: 1
Reputation: 4274
If you do not care about keys and that just the values then this is the best method to compare values and make sure the duplicates are counted.
$mag = '{"1":"1","2":"2","3":"3","4":"3"}';
$mag_evo = '1|2|3';
$test1 = array_values(json_decode($mag, true));
$test2 = array_values(explode('|', $mag_evo));
if($test1 == $test2) {
echo 'true';
}
This will not echo true as $mag has 2 values in the array that equal 3.
This works best if you only care about the values and keys and you do not care about duplication. $mag = '{"1":"1","2":"2","3":"3","4":"3"}'; $mag_evo = '1|2|3';
$test1 = json_decode($mag, true);
$test2 = explode('|', $mag_evo);
// There is no difference in either array.
if(!array_diff($test1, $test2) && !array_diff($test2, $test1)) {
echo 'true';
}
This will return true as all values are found in both arrays, but as noted before it does not care about duplication.
Upvotes: 0
Reputation: 2630
get the array from user or input the array values.Use sort function to sort both arrays. check using ternary operator. If the both arrays are equal it will print arrays are equal else it will print arrays are not equal. there is no loop iteration here.
sort($a1);
sort($a2);
echo (($a1==$a2) ? "arrays are equal" : "arrays are not equal");
Upvotes: 1
Reputation: 198237
Comparing two arrays to have equal values (duplicated or not, type-juggling taking into account) can be done by using array_diff()
into both directions:
!array_diff($a, $b) && !array_diff($b, $a);
This gives TRUE
if both arrays have the same values (after type-juggling). FALSE
otherwise. Examples:
function array_equal_values(array $a, array $b) {
return !array_diff($a, $b) && !array_diff($b, $a);
}
array_equal_values([1], []); # FALSE
array_equal_values([], [1]); # FALSE
array_equal_values(['1'], [1]); # TRUE
array_equal_values(['1'], [1, 1, '1']); # TRUE
As this example shows, array_diff
leaves array keys out of the equation and does not care about the order of values either and neither about if values are duplicated or not.
If duplication has to make a difference, this becomes more tricky. As far as "simple" values are concerned (only string and integer values work), array_count_values()
comes into play to gather information about which value is how often inside an array. This information can be easily compared with ==
:
array_count_values($a) == array_count_values($b);
This gives TRUE
if both arrays have the same values (after type-juggling) for the same amount of time. FALSE
otherwise. Examples:
function array_equal_values(array $a, array $b) {
return array_count_values($a) == array_count_values($b);
}
array_equal_values([2, 1], [1, 2]); # TRUE
array_equal_values([2, 1, 2], [1, 2, 2]); # TRUE
array_equal_values(['2', '2'], [2, '2.0']); # FALSE
array_equal_values(['2.0', '2'], [2, '2.0']); # TRUE
This can be further optimized by comparing the count of the two arrays first which is relatively cheap and a quick test to tell most arrays apart when counting value duplication makes a difference.
These examples so far are partially limited to string and integer values and no strict comparison is possible with array_diff
either. More dedicated for strict comparison is array_search
. So values need to be counted and indexed so that they can be compared as just turning them into a key (as array_search
does) won't make it.
This is a bit more work. However in the end the comparison is the same as earlier:
$count($a) == $count($b);
It's just $count
that makes the difference:
$table = [];
$count = function (array $array) use (&$table) {
$exit = (bool)$table;
$result = [];
foreach ($array as $value) {
$key = array_search($value, $table, true);
if (FALSE !== $key) {
if (!isset($result[$key])) {
$result[$key] = 1;
} else {
$result[$key]++;
}
continue;
}
if ($exit) {
break;
}
$key = count($table);
$table[$key] = $value;
$result[$key] = 1;
}
return $result;
};
This keeps a table of values so that both arrays can use the same index. Also it's possible to exit early the first time in the second array a new value is experienced.
This function can also add the strict context by having an additional parameter. And by adding another additional parameter would then allow to enable looking for duplicates or not. The full example:
function array_equal_values(array $a, array $b, $strict = FALSE, $allow_duplicate_values = TRUE) {
$add = (int)!$allow_duplicate_values;
if ($add and count($a) !== count($b)) {
return FALSE;
}
$table = [];
$count = function (array $array) use (&$table, $add, $strict) {
$exit = (bool)$table;
$result = [];
foreach ($array as $value) {
$key = array_search($value, $table, $strict);
if (FALSE !== $key) {
if (!isset($result[$key])) {
$result[$key] = 1;
} else {
$result[$key] += $add;
}
continue;
}
if ($exit) {
break;
}
$key = count($table);
$table[$key] = $value;
$result[$key] = 1;
}
return $result;
};
return $count($a) == $count($b);
}
Usage Examples:
array_equal_values(['2.0', '2', 2], ['2', '2.0', 2], TRUE); # TRUE
array_equal_values(['2.0', '2', 2, 2], ['2', '2.0', 2], TRUE); # TRUE
array_equal_values(['2.0', '2', 2, 2], ['2', '2.0', 2], TRUE, FALSE); # FALSE
array_equal_values(['2'], ['2'], TRUE, FALSE); # TRUE
array_equal_values([2], ['2', 2]); # TRUE
array_equal_values([2], ['2', 2], FALSE); # TRUE
array_equal_values([2], ['2', 2], FALSE, TRUE); # FALSE
Upvotes: 33
Reputation: 2981
@Cleanshooter i'm sorry but this does not do, what it is expected todo: (so does array_diff mentioned in this context)
$a1 = array('one','two');
$a2 = array('one','two','three');
var_dump(count(array_diff($a1, $a2)) === 0); // returns TRUE
(annotation: you cannot use empty on functions before PHP 5.5) in this case the result is true allthough the arrays are different.
array_diff [...] Returns an array containing all the entries from array1 that are not present in any of the other arrays.
which does not mean that array_diff
is something like: array_get_all_differences
. Explained in mathematical sets it computes:
{'one','two'} \ {'one','two','three'} = {}
which means something like all elements from first set without all the elements from second set, which are in the first set. So that
var_dump(array_diff($a2, $a1));
computes to
array(1) { [2]=> string(5) "three" }
The conclusion is, that you have to do an array_diff
in "both ways" to get all "differences" from the two arrays.
hope this helps :)
Upvotes: 13
Reputation: 1976
Conclusion from the commentary here:
Comparison of array values being equal (after type juggling) and in the same order only:
array_values($a1) == array_values($a2)
Comparison of array values being equal (after type juggling) and in the same order and array keys being the same and in the same order:
array_values($a1) == array_values($a2) && array_keys($a1) == array_keys($a2)
Upvotes: 2
Reputation:
if(count($a1) == count($a2)){
$result= array_intersect($a1, $a2);
if(count($a1) == count($result))
echo 'the same';
else
echo 'a1 different than a2';
} else
echo 'a1 different than a2';
Upvotes: -2
Reputation: 298
Compare values of two arrays:
$a = array(1,2,3);
$b = array(1,3,2);
if (array_diff($a, $b) || array_diff($b, $a)) {
echo 'Not equal';
}else{
echo 'Equal';
}
Upvotes: 0
Reputation: 4639
verify that the intersections count is the same as both source arrays
$intersections = array_intersect($a1, $a2);
$equality = (count($a1) == count($a2)) && (count($a2) == count($intersections)) ? true : false;
Upvotes: 0
Reputation: 886
As far as I can tell, there isn't a single built-in function that'll do it for you, however, something like:
if (count($a) == count($b) && (!count(array_diff($a, $b))) {
// The arrays are the same
}
Should do the trick
Upvotes: -2
Reputation: 1828
A speedy method for comparing array values which can be in any order...
function arrays_are_same($array1, $array2) {
sort($array1);
sort($array2);
return $array1==$array2;
}
So for...
$array1 = array('audio', 'video', 'image');
$array2 = array('video', 'image', 'audio');
arrays_are_same($array1, $array2)
will return TRUE
Upvotes: 1
Reputation: 1204
try this :
$array1 = array("street" => array("Althan"), "city" => "surat", "state" => "guj", "county" => "india");
$array2 = array("street" => array("Althan"), "city" => "surat", "state" => "guj", "county" => "india");
if (array_compare($array1, $array2))
{
echo "<pre>";
print_r("succsses..!");
echo "</pre>";
exit;
}
else
{
echo "<pre>";
print_r("Faild..!");
echo "</pre>";
exit;
}
function array_compare($op1, $op2)
{
foreach ($op1 as $key => $val)
{
if (is_array($val))
{
if (array_compare($val, $op2[$key]) === FALSE)
return false;
}
else
{
if (!array_key_exists($key, $op2))
{
return false; // uncomparable
}
elseif ($val < $op2[$key])
{
return false;
}
elseif ($val > $op2[$key])
{
return false;
}
}
}
return true; // $op1 == $op2
}
Upvotes: -1