php array search by value

PHP Multidimensional Array Searching (Find key by specific value)

I have this multidimensional array. I need to search it and return only the key that matches the value of the «slug». I know there are other threads about searching multidimensional arrays, but I’m not really understanding enough to apply to my situation. Thanks very much for any help!

So I need a function like:

8 Answers 8

Another poossible solution is based on the array_search() function. You need to use PHP 5.5.0 or higher.

Example

Explanation

Summary

So you could use it as:

The original example(by xfoxawy) can be found on the DOCS.
The array_column() page.

Update

Due to Vael comment I was curious, so I made a simple test to meassure the performance of the method that uses array_search and the method proposed on the accepted answer.

I created an array which contained 1000 arrays, the structure was like this (all data was randomized):

I ran the search test 100 times searching for different values for the name field, and then I calculated the mean time in milliseconds. Here you can see an example.

Results were that the method proposed on this answer needed about 2E-7 to find the value, while the accepted answer method needed about 8E-7.

Like I said before both times are pretty aceptable for an application using an array with this size. If the size grows a lot, let’s say 1M elements, then this little difference will be increased too.

Update II

Update III

Thanks to @mickmackusa for spotting several limitations on this method:

Источник

How to search by key=>value in a multidimensional array in PHP

Is there any fast way to get all subarrays where a key value pair was found in a multidimensional array? I can’t say how deep the array will be.

Simple example array:

When I search for key=name and value=»cat 1″ the function should return:

I guess the function has to be recursive to get down to the deepest level.

16 Answers 16

The key there is that search_r takes its fourth parameter by reference rather than by value; the ampersand & is crucial.

How about the SPL version instead? It’ll save you some typing:

What’s great is that basically the same code will iterate through a directory for you, by using a RecursiveDirectoryIterator instead of a RecursiveArrayIterator. SPL is the roxor.

The only bummer about SPL is that it’s badly documented on the web. But several PHP books go into some useful detail, particularly Pro PHP; and you can probably google for more info, too.

php array search by value. Смотреть фото php array search by value. Смотреть картинку php array search by value. Картинка про php array search by value. Фото php array search by value

Came back to post this update for anyone needing an optimisation tip on these answers, particulary John Kugelman’s great answer up above.

His posted function work fine but I had to optimize this scenario for handling a 12 000 row resultset. The function was taking an eternal 8 secs to go through all records, waaaaaay too long.

I simply needed the function to STOP searching and return when match was found. Ie, if searching for a customer_id, we know we only have one in the resultset and once we find the customer_id in the multidimensional array, we want to return.

Here is the speed-optimised ( and much simplified ) version of this function, for anyone in need. Unlike other version, it can only handle only one depth of array, does not recurse and does away with merging multiple results.

This brought down the the task to match the 12 000 records to a 1.5 secs. Still very costly but much more reasonable.

php array search by value. Смотреть фото php array search by value. Смотреть картинку php array search by value. Картинка про php array search by value. Фото php array search by value

A minor imporvement to the fast version.

php array search by value. Смотреть фото php array search by value. Смотреть картинку php array search by value. Картинка про php array search by value. Фото php array search by value

Be careful of linear search algorithms (the above are linear) in multiple dimensional arrays as they have compounded complexity as its depth increases the number of iterations required to traverse the entire array. Eg:

would take at the most 200 iterations to find what you are looking for (if the needle were at [100][1]), with a suitable algorithm.

Linear algorithms in this case perform at O(n) (order total number of elements in entire array), this is poor, a million entries (eg a 1000x100x10 array) would take on average 500,000 iterations to find the needle. Also what would happen if you decided to change the structure of your multidimensional array? And PHP would kick out a recursive algorithm if your depth was more than 100. Computer science can do better:

Where possible, always use objects instead of multiple dimensional arrays:

and apply a custom comparator interface and function to sort and find them:

You can use uasort() to utilize a custom comparator, if you’re feeling adventurous you should implement your own collections for your objects that can sort and manage them (I always extend ArrayObject to include a search function at the very least).

Once they are sorted (uasort is O(n log n), which is as good as it gets over arbitrary data), binary search can do the operation in O(log n) time, ie a million entries only takes

20 iterations to search. As far as I am aware custom comparator binary search is not implemented in PHP ( array_search() uses natural ordering which works on object references not their properties), you would have to implement this your self like I do.

This approach is more efficient (there is no longer a depth) and more importantly universal (assuming you enforce comparability using interfaces) since objects define how they are sorted, so you can recycle the code infinitely. Much better =)

Источник

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(); // массив результатов, для вычисления среднего значения третьего варианта

Источник

PHP multidimensional array search by value

I have an array where I want to search the uid and get the key of the array.

Examples

Assume we have the following 2-dimensional array:

I tried making loops, but I want a faster executing code.

22 Answers 22

This will work. You should call it like this:

Based on angoru answer. In later versions of PHP ( >= 5.5.0 ) you can use one-liner.

php array search by value. Смотреть фото php array search by value. Смотреть картинку php array search by value. Картинка про php array search by value. Фото php array search by value

If you are using (PHP 5 >= 5.5.0) you don’t have to write your own function to do this, just write this line and it’s done.

If you want just one result:

For multiple results

In case you have an associative array as pointed in the comments you could make it with:

If you are using PHP

In later versions of PHP (>= 5.5.0) you can use this one-liner:

php array search by value. Смотреть фото php array search by value. Смотреть картинку php array search by value. Картинка про php array search by value. Фото php array search by value

Building off Jakub’s excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):

I know this was already answered, but I used this and extended it a little more in my code so that you didn’t have search by only the uid. I just want to share it for anyone else who may need that functionality.

Here’s my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.

Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.

Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.

This second example shows you where a value (‘Taylor’) is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name ‘Taylor’ AND are employed).

Источник

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:

Источник

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

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