Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP check if arrays are identical?

Tags:

php

I'm looking for a way to check if two arrays are identical, for example

  $a = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
$b = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);

These two would be identical, but if a single value was changed, it would return false, I know I could write a function, but is there one already built?

like image 579
Saulius Antanavicius Avatar asked Nov 27 '11 03:11

Saulius Antanavicius


People also ask

How do I check if two arrays are identical in PHP?

Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important.

How can you tell if two arrays are identical?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

How do you check if an array exists in another array PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

How do I compare two arrays of arrays?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.


2 Answers

You can just use $a == $b if order doesn't matter, or $a === $b if order does matter.

For example:

$a = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
$b = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
$c = array(
    '3' => 14,
    '1' => 12,
    '6' => 11
);
$d = array(
    '1' => 11,
    '3' => 14,
    '6' => 11
);

$a == $b;   // evaluates to true
$a === $b;  // evaluates to true
$a == $c;   // evaluates to true
$a === $c;  // evaluates to false
$a == $d;   // evaluates to false
$a === $d;  // evaluates to false
like image 93
Jon Newmuis Avatar answered Sep 21 '22 19:09

Jon Newmuis


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

like image 40
Martin. Avatar answered Sep 21 '22 19:09

Martin.