php array not in array
in_array
(PHP 4, PHP 5, PHP 7, PHP 8)
in_array — Проверяет, присутствует ли в массиве значение
Описание
Список параметров
Возвращаемые значения
Примеры
Пример #1 Пример использования in_array()
Второго совпадения не будет, потому что in_array() регистрозависима, таким образом, программа выведет:
Пример #2 Пример использования in_array() с параметром strict
Результат выполнения данного примера:
Пример #3 Пример использования in_array() с массивом в качестве параметра needle
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 38 notes
Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP’s leniency on variable types, but in «real-life» is almost useless.
The solution is to use the strict checking option.
// First three make sense, last four do not
If you’re working with very large 2 dimensional arrays (eg 20,000+ elements) it’s much faster to do this.
Remember to only flip it once at the beginning of your code though!
# foo it is found in the array or one of its sub array.
For a case-insensitive in_array(), you can use array_map() to avoid a foreach statement, e.g.:
Determine whether an object field matches needle.
= array( new stdClass (), new stdClass () );
$arr [ 0 ]-> colour = ‘red’ ;
$arr [ 1 ]-> colour = ‘green’ ;
$arr [ 1 ]-> state = ‘enabled’ ;
in_array() may also return NULL if the second argument is NULL and strict types are off.
If the strict mode is on, then this code would end up with the TypeError
In a high-voted example, an array is given that contains, amongst other things, true, false and null, against which various variables are tested using in_array and loose checking.
If you have an array like:
$arr = array(0,1,2,3,4,5);
Add an extra if() to adrian foeder’s comment to make it work properly:
If you found yourself in need of a multidimensional array in_array like function you can use the one below. Works in a fair amount of time
This code will search for a value in a multidimensional array with strings or numbers on keys.
I just struggled for a while with this, although it may be obvious to others.
If you have an array with mixed type content such as:
?>
be sure to use the strict checking when searching for a string in the array, or it will match on the 0 int in that array and give a true for all values of needle that are strings strings.
I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:
?>
I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether ‘strict’ is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.
I would like to add something to beingmrkenny at gmail dot com comparison post. After debugging a system, i discovered a security issue in our system and his post helped me find the problem.
In my additional testing i found out that not matter what you search for in an array, except for 0 and null, you get true as the result if the array contains true as the value.
Examples as php code :
Such the best practice in our case is to use strict mode. Which was not so obvious.
Kelvin’s case-insensitive in_arrayi is fine if you desire loose typing, but mapping strtolower onto the array will (attempt to) cast all array members to string. If you have an array of mixed types, and you wish to preserve the typing, the following will work:
// Note
// You can’t use wildcards and it does not check variable type
?>
A first idea for a function that checks if a text is in a specific column of an array.
It does not use in_array function because it doesn’t check via columns.
Its a test, could be much better. Do not use it without test.
Beware when using this function to validate user input:
$a = array(‘0’ => ‘Opt 1’, ‘1’ => ‘Opt 2’, ‘2’ => ‘Opt 3’);
$v = ‘sql injection’;
var_dump(in_array($v, array_keys($a)));
This will result : true;
If you need to find if a value in an array is in another array you can use the function:
The top voted notes talked about creating strict comparison function, because in_array is insufficient, because it has very lenient type checking (which is PHP default behaviour).
The thing is, in_array is already sufficient. Because as a good programmer, you should never have an array which contains
It’s better to fix how you store data and retrieve data from user, rather than fixing in_array() which is not broken.
If you’re creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it’s much faster.
Recursive in array using SPL
If array contain at least one true value, in_array() will return true every times if it is not false or null
Be careful to use the strict parameter with truth comparisons of specific strings like «false»:
?>
The above example prints:
False is truthy.
False is not truthy.
This function is for search a needle in a multidimensional haystack:
When using numbers as needle, it gets tricky:
Note this behaviour (3rd statement):
in_array(0, array(42)) = FALSE
in_array(0, array(’42’)) = FALSE
in_array(0, array(‘Foo’)) = TRUE
in_array(‘0’, array(‘Foo’)) = FALSE
Watch out for this:
Yes, it seems that is_array thinks that a random string and 0 are the same thing.
Excuse me, that’s not loose checking, that’s drunken logic.
Or maybe I found a bug?
hope this function may be useful to you, it checks an array recursively (if an array has sub-array-levels) and also the keys, if wanted:
If you have a multidimensional array filled only with Boolean values like me, you need to use ‘strict’, otherwise in_array() will return an unexpected result.
Hope this helps somebody, cause it took me some time to figure this out.
If you search for numbers, in_array will convert any strings in your array to numbers, dropping any letters/characters, forcing a numbers-to-numbers comparison. So if you search for 1234, it will say that ‘1234abcd’ is a match. Example:
Esta función falla con las letras acentuadas y con las eñes. Por tanto, no sirve para los caracteres UTF-8.
El siguiente código falla para na cadena = «María Mañas», no reconoce ni la «í» ni la «ñ»:
// ¿La cadena está vacía?
if (empty ($cadena))
<
$correcto = false;
>
else
<
$nombreOapellido = mb_strtoupper ($cadena, «utf-8»);
$longitudCadena = mb_strlen ($cadena, «utf-8»);
Esta función falla con las letras acentuadas y con las eñes. Por tanto, no sirve para los caracteres UTF-8.
El siguiente código falla para na cadena = «María Mañas», no reconoce ni la «í» ni la «ñ»:
// ¿La cadena está vacía?
if (empty ($cadena))
<
$correcto = false;
>
else
<
$nombreOapellido = mb_strtoupper ($cadena, «utf-8»);
$longitudCadena = mb_strlen ($cadena, «utf-8»);
I needed a version of in_array() that supports wildcards in the haystack. Here it is:
$haystack = array( ‘*krapplack.de’ );
$needle = ‘www.krapplack.de’ ;
var_dump(in_array(‘invalid’, array(0,10,20)));
The above code gives true since the ‘invalid’ is getting converted to 0 and checked against the array(0,10,20)
but var_dump(in_array(‘invalid’, array(10,20))); gives ‘false’ since 0 not there in the array
A function to check an array of values within another array.
Second element ‘123’ of needles was found as first element of haystack, so it return TRUE.
If third parameter is not set to Strict then, the needle is found in haystack eventhought the values are not same. the limit behind the decimal seems to be 6 after which, the haystack and needle match no matter what is behind the 6th.
In PHP array function the in_array() function mainly used to check the item are available or not in array.
1. Non-strict validation
2. Strict validation
1. Non-strict validation:
This method to validate array with some negotiation. And it allow two parameters.
Note: the Example 1, we use only two parameter. Because we can’t mention `false` value. Because In default the in_array() take `false` as a boolean value.
In above example,
Example 1 : The `key1` is not value in the array. This is key of the array. So this scenario the in_array accept the search key as a value of the array.
Example 2: The value `577` is not in the value and key of the array. It is some similar to the value `579`. So this is also accepted.
So this reason this type is called non-strict function.
2. Strict validation
This method to validate array without any negotiation. And it have three parameters. If you only mention two parameter the `in_array()` function take as a non-strict validation.
This is return `true` only the search string is match exactly with the array value with case sensitivity.
Checking to see if one array’s elements are in another array in PHP
I have two arrays in PHP as follows:
How do I check if any of the People elements are in the Wanted Criminals array?
In this example, it should return true because 20 is in Wanted Criminals.
7 Answers 7
There’s little wrong with using array_intersect() and count() (instead of empty).
if ’empty’ is not the best choice, what about this:
That code is invalid as you can only pass variables into language constructs. empty() is a language construct.
You have to do this in two lines:
Performance test for in_array vs array_intersect:
Here are the results:
in_array is at least 5 times faster. Note that we «break» as soon as a result is found.
You could also use in_array as follows:
While array_intersect is certainly more convenient to use, it turns out that its not really superior in terms of performance. I created this script too:
Then, I ran both snippets respectively at: http://3v4l.org/WGhO7/perf#tabs and http://3v4l.org/g1Hnu/perf#tabs and checked the performance of each. The interesting thing is that the total CPU time, i.e. user time + system time is the same for PHP5.6 and the memory also is the same. The total CPU time under PHP5.4 is less for in_array than array_intersect, albeit marginally so.
Here’s a way I am doing it after researching it for a while. I wanted to make a Laravel API endpoint that checks if a field is «in use», so the important information is: 1) which DB table? 2) what DB column? and 3) is there a value in that column that matches the search terms?
Knowing this, we can construct our associative array:
Then, we can set our values that we will check:
Then, we can use array_key_exists() and in_array() with eachother to execute a one, two step combo and then act upon the truthy condition:
I apologize for the Laravel-specific PHP code, but I will leave it because I think you can read it as pseudo-code. The important part is the two if statements that are executed synchronously.
array_key_exists() and in_array() are PHP functions.
and then you could make GET requests such as:
GET /in-use/accounts/account_name/Bob’s Drywall (you may need to uri encode the last part, but usually not)
Notice also that no one can do:
PHP: array_key_exists ищет быстрее чем in_array в 500 раз
В 2014 уже писали про обыск массива, но вряд ли кто понял.
C тех пор вышло много версий PHP и не исправили значит обратная связь плохая и об этом мало кто знает. На питоне так же, и в 3* хуже чем в 2.7.
Иногда нужно найти строку в массиве строк — очень частая операция в разных алгоритмах и если массив небольшой и искать немного и не в цикле, то in_array нормально, на общую скорость не влияет, но если big data и искать надо массиве из миллиарда строк и миллиард раз, то это уже критично: лучше час вместо недели.
Простой тест показывает:
in_array ищет за 6-9 сек ideone.com/Yb1mDa 6600ms
а array_key_exists ищет тоже самое, но быстрее в 250(php5.6/py3.*) в 400+ раз (php7.3/py2.7) ideone.com/gwSmFc (цикл увеличен в 100 раз) 12ms (6600/12=550раз +-10% разброс из-за нагрузки и кеша)
Почему же такое происходит? Рассмотрим подробно:
1) Поиск строк на чистом ассемблере/си это сортировка массива строк (быстрая или пузырьковая), затем бинарный поиск.
Число шагов в бинарном поиске log(n) раз и зависит от размера массива, и намного меньше чем простой перебор.
Отсортировать массив строк можно заранее, один раз и закешировать, а потом делать миллиард поисков. Но это не помогает.
По умолчанию сортировка происходит каждый раз снова, хотя писали что улучшили в 7.2 in_array через хеш, но немного.
Размер хеша, алгоритм хеширования зашит в движок пхп и его не поменять, хотя исходники открыты- можно скачать изменить и скомпилировать если сервер свой.
Дальше можно не читать, меняйте in_array на array_combine + array_key_exists и всё.
Число шагов при поиске по хешу зависит от количества коллизий и кол-ва строк с одинаковым хешем. Их нужно перебирать или также сортировать и бинарный поиск.
Для уменьшения коллизий можно выделить больше памяти, если возможно, что сейчас не такая проблема, как 50 лет назад когда 1 кб памяти на магн.катушках стоил как самолет. А именно тогда были придуманы все основные алгоритмы: sort/zip/gif/jpg/итд — им не надо много памяти, но они плохие, сейчас есть намного лучше, но им надо много памяти 1-16 Мб. Да, есть серверы с 256 Мб и на каждого отдельный поток и 16 Мб уже много, но на девайсе среднего юзера 1 Гб как минимум и 16 Мб это капля в море.
Еще больший эффект можно получить если заменить вызов функции array_key_exists на конструкцию isset($mphp array not in array), она не чистит очередь команд и кеш, не использует стек и быстрее где-то на 20%.
Так же можно еще ускорить если создать массив 2х первых букв- 4*16кб и искать сначала по смещению (индекс=код 1го символа + 2го*256) указатель на массив хешей для остальной части строки, затем ищем уже среди маленького массива «хвостов» строк и коллизий на порядок меньше.
Это требует еще больше памяти и алгоритм сложнее, но поиск быстрее в 30+ раз. Но в пхп это не реализовано, можно написать свою библиотеку so/dll и вызывать, или попросить разработчиков добавить в 7.5.
Можно искать через mySQL, но надо группировать запросы и это будет все равно медленней.
in_array() and multidimensional array
I use in_array() to check whether a value exists in an array like below,
or I shouldn’t be using in_array() when comes to the multidimensional array?
23 Answers 23
in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:
If you know which column to search against, you can use array_search() and array_column():
This idea is in the comments section for array_search() on the PHP manual;
This will work too.
in_array only operates on a one dimensional array, so you need to loop over each sub array and run in_array on each.
As others have noted, this will only for for a 2-dimensional array. If you have more nested arrays, a recursive version would be better. See the other answers for examples of that.
if your array like this
For Multidimensional Children: in_array(‘needle’, array_column($arr, ‘key’))
Great function, but it didnt work for me until i added the if($found) < break; >to the elseif
You could always serialize your multi-dimensional array and do a strpos :
Various docs for things I used:
Since PHP 5.6 there is a better and cleaner solution for the original answer :
With a multidimensional array like this :
We can use the splat operator :
If you have string keys like this :
You will have to use array_values in order to avoid the error Cannot unpack array with string keys :
I believe you can just use array_key_exists nowadays:
The accepted solution (at the time of writing) by jwueller
Due to PHP’s type juggling when comparing values of different type both
If this is not the desired behaviuor it can be convenient to cast numeric values to string before doing a non-strict comparison: