PHP - Check If Two Arrays Are Equal

PHP - Check if two arrays are equal

$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.

See Array Operators.

EDIT

The inequality operator is != while the non-identity operator is !== to match the equality
operator == and the identity operator ===.

PHP check if arrays are identical?

You can use

$a === $b // or $a == $b

example of usage:

<?php
$a = array(
'1' => 12,
'3' => 14,
'6' => 11
);
$b = array(
'1' => 12,
'3' => 14,
'6' => 11
);
echo ($a === $b) ? 'they\'re same' : 'they\'re different';

echo "\n";
$b['1'] = 11;

echo ($a === $b) ? 'they\'re same' : 'they\'re different';

which will return

they're same
they're different

demo

Check if two arrays have the same values

sort($a);
sort($b);
if ($a===$b) {//equal}

How to check if Two Arrays Have Same Elements Regardless of Their Index Position

Use Array Diff :

$a = array("apple","banana", "strawberry");
$b = array("strawberry", "apple","banana");


$result = array_diff($a, $b);

if(count($result) > 0){
echo "yes";
}else{
echo "no";
}

How to check if two arrays contain the same values?

I would do array_diff() which check difference between two arrays.

$areEqual = array_diff($a, $b) === array_diff($b, $a);

or

$areEqual = !(array_diff($a, $b) || array_diff($b, $a));

Is there a built-in function for PHP for me to check whether two arrays contain the same values ( order is important?)

You have a couple of options depending on what you want:

just use a straight if

 if($array === $array2)

or you can use array_diff which will give you an output array of any differences.

 $diff = array_diff($array, $array2)

PHP: Built-in function to check whether two Array values are equal ( Ignoring the order)

array_diff looks like an option:

function array_equal($a1, $a2) {
return !array_diff($a1, $a2) && !array_diff($a2, $a1);
}

or as an oneliner in your code:

if(!array_diff($a1, $a2) && !array_diff($a2, $a1)) doSomething();


Related Topics



Leave a reply



Submit