Содержит ли массив элемент php
PHP: Поиск в массиве
Поиск значения в массиве требуется практически в каждом PHP приложении, скрипте работающим с данными, для чего существует множество способов и специальных функций. В зависимости от задачи и типа поиска следует использовать те или иные инструменты, учитывая их особенности, скорость выполнения и удобство в применении. Далее мы ознакомимся с PHP функциями поиска элементов в массиве, возможными конструкциями и методами, а также выясним какой способ наиболее быстрый.
Функции для поиска в массиве:
array_search — служит для поиска значения в массиве. В случае удачи она возвращает ключ искомого значения, если ничего не найдено — возвращает FALSE. До версии PHP 4.2.0, array_search() при неудаче возвращала NULL, а не FALSE.
Синтаксис функции mixed array_search ( mixed needle, array haystack [, bool strict] ).
Если значение needle (то, что ищем в массиве), является строкой, то производится регистро-зависимое сравнение.
Если передать в функцию в качестве третьего параметра (это не обязательно) значение TRUE, то поиск будет производится с учетом типа переменной.
Стоит учитывать, если искомое значение встречается в массиве несколько раз, то функция вернет только один — первый найденный ключ.
in_array — Проверяет, присутствует ли в массиве значение, в случае успеха возвращает TRUE, неудачи FALSE. Как вы понимаете функция служит для поиска и определения наличия элемента в массиве, ключ на сам же элемент не возвращается.
Функции для перебора элементов массива, с последующим поиском:
foreach — Перебирает элементы массива, работает только с массивами и объектами, в случае использования переменных отличного типа, PHP выдаст ошибку.
Возможны два вида синтаксиса (подробнее тут):
Пример использования функции с конструкцией foreach для поиска элемента массива, возвращает TRUE при успехе
Возвращает ключ элемента массива при успехе
while — цикл, с помощью которого также можно произвести поиск элемента в массиве. Подробнее о самой конструкции, тут.
Синтаксис конструкции
while (expr)
statement
Возвращает ключ элемента массива при успехе
Из выше описанных примеров видно, что одни методы служат для поиска элемента в одномерных массивах, другие позволяют организовать поиск в многомерных массивах. Выбор метода зависит от типа обрабатываемых данных, будь то простой массив, или сложные многомерные деревья.
Далее произведем замер среднего времени выполнения функций поиска:
Число элементов массива | array_search | Цикл foreach | Цикл while |
10 | 0.0000068 | 0.0000064 | 0.0000076 |
100 | 0.0000078 | 0.0000153 | 0.0000185 |
1000 | 0.0000209 | 0.0001177 | 0.0001351 |
10000 | 0.0004210 | 0.0012128 | 0.0018670 |
100000 | 0.0039679 | 0.0130989 | 0.0175215 |
Из приведенной таблицы замеров видно, что функция array_search, показывает наилучший результат как при поиске в малых так и больших массивах. При этом время поиска спомощью циклов значительно увеличивается в зависимости от размера массива.
Проверка на массив, на наличие элементов и на пустоту в PHP
В этой статье будем делать различные проверки массива. В том числе проверим является ли переменная массивом, а так же проверим есть ли у ключей массива пустые значения. Будем двигаться от простого к более сложному. И первое, что можно сделать, это проверить на массив. Для этого нам помоет встроенная в язык PHP функция is_array. Разберем небольшой пример.
$arr = [‘id’, ‘name’, ’email’]; // Массив элементов if(is_array($arr))< echo 'Это массив'; >else
Функция вернет true, если это массив и false — если не массив. Это простой пример и сложностей возникнуть не должно. Перейдем к следующему примеру.
Проверка массива на пустоту и пустые элементы в PHP
Функция empty сработает только в том случае, когда в массиве нет вообще никаких элементов. Поэтому ее лучше не использовать при проверке массивов. В этом случае нам поможет еще одна функция — array_diff. С ее помощью мы сравним исходный массив с другим массивом и в случае расхождения выведем элементы массива, которые не совпадают. Может быть немного сумбурно и не понятно, но давайте разберем на примере.
array(8) < [0]=>string(4) «name» [1]=> string(0) «» [2]=> string(3) «num» [3]=> [4]=> string(0) «» [5]=> [6]=> string(4) «Alex» [7]=> string(0) «» > array(3) < [0]=>string(4) «name» [2]=> string(3) «num» [6]=> string(4) «Alex» >
Функция пропустит все пустые элемент массива, в том числе NULL и false и выведет только те, в которых что-то есть. Мы так же можем проверить какой именно элемент массива был пустой с помощью цикла for.
array(4) < ["age"]=>int(34) [«name»]=> string(4) «Ivan» [«city»]=> string(0) «» [«number»]=> string(0) «» > array(2) < ["age"]=>int(34) [«name»]=> string(4) «Ivan» >
Проверить наличие элемента в массиве
Для этих целей подойдет функция in_array. Она проверяет на присутствие в массиве значения.
Первым аргументом указываем что будем искать, вторым — где. На этом по работе с массивами окончен. Надеюсь, что вам в нем все было понятно. Но если остались какие-то вопросы, задавайте их в комментариях.
Website-create.ru
Зачастую при написании кода необходимо проверить существует ли то или иное значение элемента в массиве. Сегодня мы рассмотрим несколько функций, при помощи которых это можно сделать.
Проверка наличия значения элемента в массиве может применяться при решении различных задач в программировании.
Мы можем получать различные массивы из нашей базы данных и проверять наличие того или иного значения в нем. Искомое значение может передаваться и от пользователя нашего скрипта, когда он, например, что-то ищет. По результатам такого поиска можно совершать определенные действия. Все зависит от конкретно поставленной задачи, однако, алгоритмы поиска значения в массиве будут одними и теми же.
Сегодня мы их рассмотрим.
Проверка наличия значения в массиве. Функция in_array()
Функция in_array() позволит нам проверить наличие какого-либо значения в массиве.
Если результат ее работы удачный и искомый элемент в массиве найден, то функция вернет true, то есть «правду».
Также нужно помнить, что функция осуществляет сравнение с учетом регистра символов.
Давайте рассмотрим работу этой функции на простом примере.
Нам нужен какой-нибудь массив. При помощи функции проверим наличие значения в массиве и выведем на экран определенное сообщение.
Отработав функция выведет на экран сообщение «Yes», так как элемент «Marina» в нашем массиве присутствует.
Поменяйте первый параметр в функции на какой-либо несуществующий элемент, и Вы увидите сообщение «No».
Проверка наличия значения в массиве. Функция array_search()
Существует и еще одна функция для поиска array_search(), которая в отличие от предыдущей будет возвращать ключ найденного элемента. Это в свою очередь может пригодиться, если мы работаем с ассоциативным массивом.
Функция принимает те же параметры, что и предыдущая. При этом третий параметр также является необязательным.
Давайте посмотрим, как ее можно использовать, работая с ассоциативным массивом.
В данном случае мы увидим на экране «name», то есть ключ от искомого элемента со значением «Mila».
Эти две функции очень похожи и по сути отличаются только возвращаемым значением.
Поиск значения в многомерном массиве
А что делать, если мы работаем с многомерным массивом? Ведь его элементами будут другие массивы.
Здесь уже рассмотренные нами алгоритмы не сработают.
На самом деле все не так уж и сложно, просто нужно немного усложнить весь механизм и использовать цикл, например, foreach(), который прекрасно работает с массивами.
Допустим у нас есть многомерный массив. Его непосредственными значениями являются другие массивы, в которых может содержаться искомое значение элемента.
Все, что требуется сделать – это перебрать элементы первоначального массива в цикле foreach(). Каждый элемент этого массива будет разобран на ключ ($key) и значение ($value).
Значением будет являться каждый из массивов, находящийся внутри основного многомерного массива. Вот с этими значениями мы и будем работать, ища в каждом внутреннем массиве искомое значение элемента.
При нахождении мы выведем на экран сообщение о том, что такой элемент существует, а если нет, то выведем другое сообщение, что такого элемента нет.
Давайте посмотрим все это на примере кода:
Как Вы видите, вначале мы объявляем сам многомерный массив.
При этом здесь обязательно нужно писать не просто знак равенства, а «.=».
Как Вы поняли, итогом работы этого кода будет сообщение «OK! Element here!».
Попробуйте поменять искомый элемент на несуществующий и Вы увидите сообщение «No have element!».
Конечно же, при нахождении или не нахождении определенного элемента мы можем не просто выводить сообщения, а делать какие-либо другие действия. Все зависит от того, что Вам нужно сделать. Например, при наличии искомого значения в массиве, Вы можете отдавать пользователю какую-то конкретную информацию и т.д.
Вот и все на сегодня! Надеюсь, урок был понятен и полезен! Попробуйте сами написать подобный код, чтобы разобраться во всем окончательно.
А я жду Ваших комментариев.
Делитесь уроком со своими друзьями при помощи кнопок соц. сетей, расположенных ниже. А также подписывайтесь на обновления блога. Мы уже собрали достаточно неплохой архив полезных материалов, и они будут только пополняться!
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.
Функции для работы с массивами
Содержание
User Contributed Notes 14 notes
A simple trick that can help you to guess what diff/intersect or sort function does by name.
Example: array_diff_assoc, array_intersect_assoc.
Example: array_diff_key, array_intersect_key.
Example: array_diff, array_intersect.
Example: array_udiff_uassoc, array_uintersect_assoc.
This also works with array sort functions:
Example: arsort, asort.
Example: uksort, ksort.
Example: rsort, krsort.
Example: usort, uasort.
?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>
Updated code of ‘indioeuropeo’ with option to input string-based keys.
Here is a function to find out the maximum depth of a multidimensional array.
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)
Short function for making a recursive array copy while cloning objects on the way.
If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.
to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);
You can also stringify objects, numbers, etc.
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:
I was looking for an array aggregation function here and ended up writing this one.
Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.