php поиск в строке элементов массива

PHP: Поиск в массиве

php поиск в строке элементов массива. Смотреть фото php поиск в строке элементов массива. Смотреть картинку php поиск в строке элементов массива. Картинка про 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
100.00000680.00000640.0000076
1000.00000780.00001530.0000185
10000.00002090.00011770.0001351
100000.00042100.00121280.0018670
1000000.00396790.01309890.0175215

Из приведенной таблицы замеров видно, что функция array_search, показывает наилучший результат как при поиске в малых так и больших массивах. При этом время поиска спомощью циклов значительно увеличивается в зависимости от размера массива.

Источник

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 ; all in one array anyway.

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.

Источник

PHP: array_search — быстрый поиск по массиву

Я уже достаточно долго использую функцию array_search() для поиска значений в массиве, так как неоднократно слышал и читал о том, что она работает заметно быстрее, чем поиск по массиву в цикле, но насколько она быстрее — не знал. Наконец-то дошли руки самому проверить и посчитать.

Сравнил скорость поиска в массиве с помощью этой функции с обычным перебором массива в циклах foreach и while. На 10-100 элементах массива разница незаметна да и время столь мало, что им можно принебречь. А вот для больших массивов разница оказалась весьма существенной. С увеличением размера массива на порядок, значительно увеличивалось и время поиска. При ста тысячах элементов скорость foreach падала до 0,013 секунды, а while — до 0,017, при том что array_search() тоже замедлился, но все-таки остался на порядок быстрее — 0.004 секунды. Для большого скрипта, работающего с большими массивами замена поиска в цикле на поиск с помощью array_search() будет вовсе не «блошиной оптимизацией».

UPD: добавил в циклы break и менял искомое значение так, чтобы оно было в середине массива — 5-50-500 и т.д. Данные в таблице обновленные.

Число элементов массиваarray_searchЦикл foreachЦикл while
100.00000680.00000640.0000076
1000.00000780.00001530.0000185
10000.00002090.00011770.0001351
100000.00042100.00121280.0018670
1000000.00396790.01309890.0175215

В связи с этим вспомнил недавнюю дискуссию с одним из коллег на работе — насчет того, нужно ли программисту знать все эти встроенные функции языка, или достаточно «программистского склада ума» и общих познаний. Не вдаваясь с рассуждения об этом самом складе ума, думаю, что все-таки знать функции надо, может быть не весь синтаксис в деталях, а хотя-бы какие функции есть и что они в общих чертах могут.

UPD: нужен программистский склад ума, тоже нужен! И внимательность с памятью не помешают (навеяно break и range 🙂

Под хабракатом код скрипта, которым подсчитывал время:

$mass=100000; // число значений в массиве в котором будем искать
$search=50000; // в массиве будем искать это значение
$first_result=array(); // массив результатов, для вычисления среднего значения первого варианта
$second_result=array(); // массив результатов, для вычисления среднего значения второго варианта
$third_result=array(); // массив результатов, для вычисления среднего значения третьего варианта

Источник

array_search

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

array_search — Осуществляет поиск данного значения в массиве и возвращает ключ первого найденного элемента в случае успешного выполнения

Описание

Список параметров

Если needle является строкой, сравнение происходит с учётом регистра.

Возвращаемые значения

Примеры

Пример #1 Пример использования array_search()

Смотрите также

User Contributed Notes 44 notes

in (PHP 5 >= 5.5.0) you don’t have to write your own function to search through a multi dimensional array

$userdb=Array
(
(0) => Array
(
(uid) => ‘100’,
(name) => ‘Sandra Shush’,
(url) => ‘urlof100’
),

(1) => Array
(
(uid) => ‘5465’,
(name) => ‘Stefanie Mcmohn’,
(pic_square) => ‘urlof100’
),

(2) => Array
(
(uid) => ‘40489’,
(name) => ‘Michael’,
(pic_square) => ‘urlof40489’
)
);

simply u can use this

$key = array_search(40489, array_column($userdb, ‘uid’));

About searcing in multi-dimentional arrays; two notes on «xfoxawy at gmail dot com»;

It perfectly searches through multi-dimentional arrays combined with array_column() (min php 5.5.0) but it may not return the values you’d expect.

Secondly, if your array is big, I would recommend you to first assign a new variable so that it wouldn’t call array_column() for each element it searches. For a better performance, you could do;

It’s what the document stated «may also return a non-Boolean value which evaluates to FALSE.»

the recursive function by tony have a small bug. it failes when a key is 0

here is the corrected version of this helpful function:

If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match. Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null. This nuance cost me a lot of time and sanity, so I hope this helps someone. In case you don’t know what I’m talking about, here’s an example:

hallo every body This function matches two arrays like
search an array like another or not array_match which can match

for searching case insensitive better this:

About searcing in multi-dimentional arrays;
note on «xfoxawy at gmail dot com» and turabgarip at gmail dot com;

$xx = array_column($array, ‘NAME’, ‘ID’);
will produce an array like :
$xx = [
[ID_val] => NAME_val
[ID_val] => NAME_val
]

$yy = array_search(‘tesxt’, array_column($array, ‘NAME’, ‘ID’));
will output expected ID;

To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.

Take the following two arrays you wish to search:

I was going to complain bitterly about array_search() using zero-based indexes, but then I realized I should be using in_array() instead.

The essence is this: if you really want to know the location of an element in an array, then use array_search, else if you only want to know whether that element exists, then use in_array()

Be careful when search for indexes from array_keys() if you have a mixed associative array it will return both strings and integers resulting in comparison errors

/* The above prints this, as you can see we have mixed keys
array(3) <
[0]=>
int(0)
[1]=>
string(3) «car»
[2]=>
int(1)
>
*/

hey i have a easy multidimensional array search function

Despite PHP’s amazing assortment of array functions and juggling maneuvers, I found myself needing a way to get the FULL array key mapping to a specific value. This function does that, and returns an array of the appropriate keys to get to said (first) value occurrence.

But again, with the above solution, PHP again falls short on how to dynamically access a specific element’s value within the nested array. For that, I wrote a 2nd function to pull the value that was mapped above.

I needed a way to return the value of a single specific key, thus:

Better solution of multidimensional searching.

FYI, remember that strict mode is something that might save you hours.

one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings. (or even a string that looks like a number)

The problem is that unless you specify «strict» the match is done using == and in that case any string will match a numeric value of zero which is not what you want.

also, php can lookup an index pretty darn fast. for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.

//very fast lookup, this beats any other kind of search

I had an array of arrays and needed to find the key of an element by comparing actual reference.
Beware that even with strict equality (===) php will equate arrays via their elements recursively, not by a simple internal pointer check as with class objects. The === can be slow for massive arrays and also crash if they contain circular references.

This function performs reference sniffing in order to return the key for an element that is exactly a reference of needle.

A simple recursive array_search function :

A variation of previous searches that returns an array of keys that match the given value:

I needed a function, that returns a value by specifying a keymap to the searched value in a multidimensional array and came up with this.

My function get_key_in_array() needed some improvement:

An implementation of a search function that uses a callback, to allow searching for objects of arbitrary complexity:

For instance, if you have an array of objects with an id property, you could search for the object with a specific id like this:

For a more complex example, this function takes an array of key/value pairs and returns the key for the first item in the array that has all those properties with the same values.

The final step is a function that returns the item, rather than its key, or null if no match found:

Источник

Php поиск в строке элементов массива

В этой статье, я разберу одну достаточно частную и частую проблему, которая может возникнуть в процессе разработки на php. Эта проблема является отражением не столько проблем организации языка программирования php, сколько не полного понимания некоторых особенностей этого языка начинающими программистами.

При работе в php очень часто приходится иметь дело с массивами, и в частности иногда встает задача поиска элемента в массиве, совпадающего с некоторым искомым значением. Для решения этой частной задачи, очень удобно пользоваться функцией:

Случай первый.

в результате исполнения кода получим на первый взгляд странный ответ – «город не найден». То есть элемент совпадающий с «Москва» в массиве есть, но он почему-то не «ищется» ….

Случай второй.

Аналогичная ситуация. Элемент в массиве совершенно очевидно присутствует, но в качестве результата мы получаем ответ, что «элемент не найден».

Случай третий.

Аналогично – получаем ответ «элемент не найден».

Случай четвертый.

Тоже самое, при исполнении кода получим на мониторе «элемент не найден».

Случай пятый.

«И опять, двадцать пять»…. Как говорится.

Причина возникающей ошибки и ее решение.

На самом деле причина возникающих ошибок кроется не в самой функции array_search(), а в том какой результат она возвращает и как мы его проверяем. Дело в том, что в php, как и в большинстве других языков программирования, при обработке информации, важное значение имеет не только конкретное значение переменной, но и тип данных, к которым она относится.

В частности в данном случае, функция возвращает либо «false» (тип данных boolean), либо ключ элемента в массиве. Этот ключ может представлять собой или целое число (integer), или строку (string), или вещественное число с десятичной добью (float), или специфический тип данных, обозначающий неопределенное значение (NULL). И ошибка в выше приведенных примерах связана с тем, что некоторые значения не boolean данных могут быть преобразованы в boolean. В частности, согласно самой справки php, следующие значение могут быть преобразованы в булев «false»:

Разберем каждый из перечисленных выше примеров.

Случай первый.

По умолчанию, нумерация ключей элементов массива начинается с 0, если не задано иначе специально. Соответственно, функция array_search() вернула правильный результат – номер ключа 0 (integer, целое число), но при сравнении этот результат был приведен к булеву «false», а это в свою очередь выполнило условие, что «элемент не найден».

Случай второй.

Заданы ключи элементов массива, которые являются строками, но при этом ключ искомого элемента равен пустой строке «». И при проверке условия, эта пустая строка была интерпретирована как булев «false», что опять же выполнило условие для вывода «элемент не найден».

Случай третий.

Ключи массива заданы строками, при этом ключ искомого элемента равен строке «0». Именно строке, не целому числу, а строке. Именно этот ключ функция вернула, но при проверке это значение было приведено к boolean «false».

Случай четвертый.

Ключи элементов массива заданы в виде чисел с плавающей точкой (float). Ключ целевого элемента массива оказался равен нулю (0.0), который при сравнении был рассмотрен как «false», что выполнило условие для вывода результата о том, что элемент в массиве не найден.

Случай пятый.

Решение.

Решением данной ошибки, является более строгая проверка результата работы функции array_search(). Во всех перечисленных примерах выше проверялось лишь значение возвращенного результата, без проверки типа данных к которым относится полученный ответ. Поэтому для наглядности, следовало бы во всех выше перечисленных примерах вместо строки

то есть в таком случае мы не только проверяем значение ответа функции, но и убеждаемся (в данном случае), что оно он относится к типу данных boolean.

Функция is_bool() проверяет – относится ли переданное ей значение к типу boolean.

Но, конечно же, обычно так условие никто не записывает. Так как есть специальный оператор «тождественно равно» (===) и ему противоположный «тождественно не равно» (!==). Это операторы строгой проверки, когда проверяется не только конкретное значение присланной переменной, но и тип ее данных. Поэтому для исправления ошибки во всех приведенных примерах, в блоке условия проверку следует переписать так:

тогда мы начнем получать правильные ответы от работы кода.

Обобщение.

Вообще говоря, строгая проверка, о которой говорится в этой статье, полезна и для многих других функций php, которые могут возвращать либо ошибку «false», либо какое-то вычисленное, найденное, извлеченное значение… Потому, что иногда вычисленное, найденное, извлеченное значение может совпадать со значением «false», хотя и относиться к другому типу данных (то есть любой тип данных кроме boolean).

Так что будьте внимательны. И не забывайте про типы данных, которые могут помещаться в переменные используемые в Вашем коде. И многих проблем можно избежать сразу.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *