php сравнение массивов на равенство
PHP скрипты
Apache
PHP Скрипты
Для Дизайна Сайта
Поиск по Сайту
Самоучитель. Книги.
Не поймете, какой каталог или жанр порнушки Вам подходит и возбудит вас? Советуем испытать этот каталог с порнографией с молодыми! Мы точно знаем, что Вы запросто отыщите в нем то, что заинтересует Вас и предоставит вам нереальное удовольствие от просмотра порно фильмов на этом сайте!
Сравнение массивов производится с помощью привычных для нас операторов отношений. Наибольший интерес в этом плане вызывают операторы равенства (==) и эквивалентности (===).
Массивы считаются равными, в том случае, если каждый элемент одного массива имеет один равный ему во втором, и наоборот. Равенство элементов подразумевает соответственно совпадение ключа и значения. Порядок расположения элементов при этом не играет роли (листинг 8.12).
Листинг 8.12. Сравнение массивов.
Заметьте, что индексы второго массива находятся в двойных кавычках, а значит имеют тип String. Но в данном случае сравниваются значения, а не типы, поэтому программа все равно выведет сообщение о равенстве массивов. То же самое относится к значениям элементов в массиве.
Иначе дело обстоит с оператором эквивалентности, который требует от своих операндов не только равенства значений, но и одинаковый порядок следования элементов в массиве (листинг 8.13).
Листинг 8.13. Эквивалентность массивов.
PHP-проверить, равны ли два массива
Я хотел бы проверить, равны ли два массива. Я имею в виду: тот же размер, тот же индекс, те же значения. Как я могу это сделать?
используя === как предложил пользователь, я ожидаю, что следующее будет печатать enter если хотя бы один элемент в массив(ы) разные, но на самом деле это не так.
13 ответов
редактировать
Примечание: принятый ответ работает для ассоциативных массивов, но это не будет работать, как ожидалось с индексированными массивами (описано ниже). Если вы хотите сравнить любой из них, используйте это решение. Кроме того, эта функция может не работать с многомерными массивами (из-за природы функции array_diff).
это потому, что выше означает:
чтобы решить эту проблему, использовать:
Сравнение размеров массива было добавлено (предложено super_ton), поскольку это может улучшить скорость.
попробовать сериализовать. Это позволит проверить, как хорошо вложенные подмассивов.
сравните их как другие значения:
вы можете прочитать обо всех операторах массива здесь: http://php.net/manual/en/language.operators.array.php Обратите внимание, например, что === также проверяет, что виды и порядок элементов в массивах одинаковые.
можно использовать array_diff_assoc чтобы проверить различия между ними.
рабочее короткое решение, которое работает даже с массивами, ключи которых заданы в другом порядке:
другой метод проверки равенства независимо от порядка значений работает с помощьюhttp://php.net/manual/en/function.array-intersect.php, вроде так:
вот версия, которая также работает с многомерными массивами, используя http://php.net/manual/en/function.array-uintersect.php:
этот способ позволяет ассоциативные массивы, члены которых упорядочены по-разному-например, они будут считаться равными на каждом языке, кроме php:)
использовать функцию php array_diff (array1, array2);
он вернет разницу между массивами. Если он пуст, то они равны.
проблема синтаксиса массивов
из моего pov лучше использовать array_diff, чем array_intersect, потому что с проверками такого рода различия, возвращаемые обычно, меньше, чем сходства, таким образом, преобразование bool меньше голодает памяти.
редактировать обратите внимание, что это решение для простых массивов и дополняет == и === один, опубликованный выше, который действителен только для словарей.
Операторы сравнения
Операторы сравнения, как это видно из их названия, позволяют сравнивать между собой два значения. Возможно вам будет интересно также ознакомиться с разделом Сравнение типов, в котором приведено большое количество соответствующих примеров.
switch ( «a» ) <
case 0 :
echo «0» ;
break;
case «a» : // Эта ветка никогда не будет достигнута, так как «a» уже сопоставленно с 0
echo «a» ;
break;
>
?>
Для различных типов сравнение происходит в соответствии со следующей таблицей (по порядку).
Пример #1 Сравнение булево/null
Пример #2 Алгоритм сравнения обычных массивов
Сравнение чисел с плавающей точкой
Тернарный оператор
Еще одним условным оператором является тернарный оператор «?:».
Пример #3 Присваивание значения по умолчанию
Рекомендуется избегать «нагромождения» тернарных выражений. Поведение PHP неочевидно при использовании нескольких тернарных операторов в одном выражении:
Пример #4 Неочевидное поведение тернарного оператора
// однако, он выводит ‘t’
// это происходит потому, что тернарные выражения вычисляются слева направо
// здесь вы можете видеть, что первое выражение вычисляется в ‘true’, которое
// в свою очередь вычисляется в (bool)true, таким образом возвращая истинную ветвь
// второго тернарного выражения.
?>
array_diff
(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)
array_diff — Вычислить расхождение массивов
Описание
Список параметров
Массивы, с которыми идёт сравнение
Возвращаемые значения
Примеры
Пример #1 Пример использования array_diff()
Пример #2 Пример использования array_diff() с несовпадающими типами
$source = [new S ( ‘a’ ), new S ( ‘b’ ), new S ( ‘c’ )];
$filter = [new S ( ‘b’ ), new S ( ‘c’ ), new S ( ‘d’ )];
Примечания
Смотрите также
User Contributed Notes 27 notes
array_diff(A,B) returns all elements from A, which are not elements of B (= A without B).
You should include this in the documentation more precisely, I think.
array_diff provides a handy way of deleting array elements by their value, without having to unset it by key, through a lengthy foreach loop and then having to rekey the array.
If you want a simple way to show values that are in either array, but not both, you can use this:
I´ve been looking for a array_diff that works with recursive arrays, I´ve tried the ottodenn at gmail dot com function but to my case it doesn´t worked as expected, so I made my own. I´ve haven´t tested this extensively, but I´ll explain my scenario, and this works great at that case 😀
We got 2 arrays like these:
I realy hopes that this could help some1 as I´ve been helped a lot with some users experiences. (Just please double check if it would work for your case, as I sad I just tested to a scenario like the one I exposed)
I just came upon a really good use for array_diff(). When reading a dir(opendir;readdir), I _rarely_ want «.» or «..» to be in the array of files I’m creating. Here’s a simple way to remove them:
If you just need to know if two arrays’ values are exactly the same (regardless of keys and order), then instead of using array_diff, this is a simple method:
?>
The function returns true only if the two arrays contain the same number of values and each value in one array has an exact duplicate in the other array. Everything else will return false.
my alternative method for evaluating if two arrays contain (all) identical values:
?>
may be slightly faster (10-20%) than this array_diff method:
?>
but only when the two arrays contain the same number of values and then only in some cases. Otherwise the latter method will be radically faster due to the use of a count() test before the array_diff().
Also, if the two arrays contain a different number of values, then which method is faster will depend on whether both arrays need to be sorted or not. Two times sort() is a bit slower than one time array_diff(), but if one of the arrays have already been sorted, then you only have to sort the other array and this will be almost twice as fast as array_diff().
Basically: 2 x sort() is slower than 1 x array_diff() is slower than 1 x sort().
It’s important to note that array_diff() is NOT a fast or memory-efficient function on larger arrays.
In my experience, when I find myself running array_diff() on larger arrays (50+ k/v/pairs) I almost always realize that I’m working the problem from the wrong angle.
Typically, when reworking the problem to not require array_diff(), especially on bigger datasets, I find significant performance improvements and optimizations.
If you’re not getting a count(array_diff($a1,$a2))>0 with something similar to the following arrays should use the php.net/array_diff_assoc function instead.
There is more fast implementation of array_diff, but with some limitations. If you need compare two arrays of integers or strings you can use such function:
10x faster than array_diff
Here is some code to take the difference of two arrays. It allows custom modifications like prefixing with a certain string (as shown) or custom compare functions.
I always wanted something like this to avoid listing all the files and folders you want to exclude in a project directory.
$relevantFiles = array_diff(scandir(‘somedir’), array(‘.’, ‘..’, ‘.idea’, ‘.project));
As touched on in kitchin’s comment of 19-Jun-2007 03:49 and nilsandre at gmx dot de’s comment of 17-Jul-2007 10:45, array_diff’s behavior may be counter-intuitive if you aren’t thinking in terms of set theory.
array_diff() returns a *mathematical* difference (a.k.a. subtraction) of elements in array A that are in array B and *not* what elements are different between the arrays (i.e. those that elements that are in either A or B but aren’t in both A and B).
Drawing one of those Ven diagrams or Euler diagrams may help with visualization.
As far as a function for returning what you may be expecting, here’s one:
Resubmitting. the update for takes into account comparison issues
Computes the difference of all the arrays
I’ve found a way to bypass that. I had 2 arrays made of arrays.
I wanted to extract from the first array all the arrays not found in the second array. So I used the serialize() function:
Yes you can get rid of gaps/missing keys by using:
Note that array_diff is not equivalent to
The difference is made only on the first level. If you want compare 2 arrays, you can use the code available at https://gist.github.com/wrey75/c631f6fe9c975354aec7 (including a class with an function to patch the array)
Here the basic function:
A simple multidimentional key aware array_diff function.
Based on one lad’s code, I created following function for creating something like HTML diff. I hope it will be useful.
Hi!
I tried hard to find a solution to a problem I’m going to explain here, and after have read all the array functions and possibilities, I had to create what I think should exist on next PHP releases.
What I needed, it’s some kind of Difference, but working with two arrays and modifying them at time, not returning an array as a result with the diference itself.
so basically, I wanted to delete coincidences on both arrays.
Now, I’ve some actions to do, and I know wich one I’ve to do with the values from one array or another.
With the normal DIFF I can’t, because if I’ve an array like C=1,4, I dont know if I’ve to do the Action_A with 1 or with 4, but I really know that everything in A, will go to the Action_A and everithing in B, will go to Action_B. So same happens with 4, don’t know wich action to apply.
So a call to this will be somethin’ like:
Now, why I use it precisely?
Imagine you’ve some «Events» and some users you select when create the event, can «see» this event you create. So you «share» the event with some users. Ok?
Imagine you created and Event_A, and shared with users 1,2,3.
Now you want to modify the event, and you decide to modify the users to share it. Imagine you change it to users 2,3,4.
(numbers are users ID).
So you can manage when you are going to modify, to have an array with the IDs in DDBB ($original), and then, have another array with ID’s corresponding to the users to share after modifying ($new). Wich ones you’ve to DELETE from DDBB, and wich ones do you’ve to INSERT?
If you do a simple difference or somehow, you get somethin’ like C=1,4.
You have no clue on wich one you’ve to insert or delete.
But on this way, you can know it, and that’s why:
I hope you find it useful, and I encourage PHP «makers», to add in a not distant future, somethin’ like this one natively, because I’m shure that I’m not the first one needing something like this.
array_udiff
array_udiff — Вычисляет расхождение массивов, используя для сравнения callback-функцию
Описание
Список параметров
Массивы для сравнения.
Callback-функция, используемая для сравнения.
Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим, чем второй.
Возвращаемые значения
Примеры
Пример #1 Пример использования array_udiff() с объектами класса stdClass
Результат выполнения данного примера:
Пример #2 Пример использования array_udiff() с объектами класса DateTime
// Создание календаря еженедельных встреч
$myCalendar = new MyCalendar ;
Результат выполнения данного примера:
Примечания
Смотрите также
User Contributed Notes 9 notes
I think the example given here using classes is convoluting things too much to demonstrate what this function does.
array_udiff() will walk through array_values($a) and array_values($b) and compare each value by using the passed in callback function.
Which returns the following.
Note that the compare function is used also internally, to order the arrays and choose which element compare against in the next round.
If your compare function is not really comparing (ie. returns 0 if elements are equals, 1 otherwise), you will receive an unexpected result.
I think the point being made is that array_udiff() can be used not only for comparisons between homogenous arrays, as in your example (and definitely the most common need), but it can be used to compare heterogeneous arrays, too.
Array ( [2] => Array ( [last_name] => Flagg [first_name] => Randall [phone] => 666-1000 ) )
Something interesting to note, is that the two arguments to the compare function don’t correspond to array1 and array2. That’s why there has to be logic in it to handle that either of the arguments might be pointing to the more complex employee array. (Found this out the hard way.)