PHP array_search: Search for a value in an array. PHP: array_search - fast array search Array search multidimensional array

One of the main operations when working with arrays is finding a specific value. This is what the PHP array_search () function is for. It is capable of handling both one-dimensional and associative collections, returning the key of the desired value if found in the array.

Syntax

The formalized description of the array_search () function in PHP is as follows:

Mixed array_search (mixed value, array $ collection [, bool strict])

Input parameters:

  • $ collection - the array in which the search will be performed;
  • value - desired value of any type;
  • strict is an optional boolean flag that sets a strict type-aware comparison mechanism.

Working mechanism

PHP's array_search () function compares value one by one with all values \u200b\u200bin the collection array. By default, the comparison is performed without regard to the types of the operands. This setting can be changed by setting the strict flag to TRUE. String comparisons are case sensitive.

If a match is found, the key corresponding to the element found is returned and the function terminates. Therefore, it cannot detect multiple occurrences of the desired value in the array with its help.

If no match is found, the function will return the boolean value FALSE.

You should test the returned result using the strict equality operator (\u003d\u003d\u003d). This is important because the function can return a value that is cast to FALSE, such as 0 or an empty string.

Examples of using

Example 1. When a multidimensional array is passed to the PHP function array_search (), the result of the operation will be the key of the required element.

"winter", "season2" \u003d\u003e "spring", "season3" \u003d\u003e "summer", "season4" \u003d\u003e "autumn"); $ result1 \u003d array_search ("winter", $ array); $ result2 \u003d array_search ("summer", $ array); $ result3 \u003d array_search ("april", $ array); ?\u003e

In this example, the variable $ result1 will be set to "season1", $ result2 will be equal to "season3", and $ result3 will be set to the boolean value FALSE, since the string "april" does not appear in the original array.

Example 2. The PHP array_search () function can process a one-dimensional array, considering its keys to be the next numerical indices in order.

The variable $ result will be assigned the value 1, according to the index of the "hunter" element in the $ array.

Example 3. Possible error in the analysis of the result.

"Washington", 1 \u003d\u003e "Adams", 2 \u003d\u003e "Jefferson", 3 \u003d\u003e "Madison", 4 \u003d\u003e "Monroe"); $ result \u003d array_search ("Washington", $ presidents); if (! $ result) (echo "G. Washington was not the first president of the USA";)?\u003e

So, without checking the result by strict equality, you can get an unexpected message that George Washington was not the first president of the United States.

Example 4. Only the key of the first match found is returned.

Despite the fact that the required value occurs three times in the array, the function will return only the first result found - 0. To search for multiple matches, it is recommended to use the PHP array_keys () function.

I have been using the array_search () function for searching for values \u200b\u200bin an array for quite a long time, as I have repeatedly heard and read that it works noticeably faster than searching through an array in a loop, but I did not know how much faster it is. Finally, we got around to checking and counting.

I compared the speed of searching in an array using this function with the usual iteration over an array in foreach and while loops. At 10-100 array elements, the difference is imperceptible, and the time is so short that they can be neglected. But for large arrays, the difference turned out to be very significant. With an increase in the size of the array by an order of magnitude, the search time also increased significantly. With a hundred thousand elements, the speed of foreach dropped to 0.013 seconds, and while - to 0.017, while array_search () also slowed down, but still remained an order of magnitude faster - 0.004 seconds. For a large script that works with large arrays, replacing the search in a loop with a search using array_search () will not be a "flea optimization" at all.

In this regard, I recalled a recent discussion with one of my colleagues at work - about whether a programmer needs to know all these built-in functions of the language, or whether a "programmer mindset" and general knowledge is enough. Without going into a discussion about this very mindset, I think that you still need to know the functions, maybe not all the syntax in detail, but at least what functions are there and what they can in general terms.

UPD: you need a programmer mindset, you also need it! And mindfulness with memory will not hurt (inspired by break and range :)

Under the habrakat, the script code that counted the time:

$ mass \u003d 100000; // the number of values \u200b\u200bin the array in which we will search
$ search \u003d 50,000; // we will search for this value in the array
$ first_result \u003d array (); // array of results, to calculate the average of the first option
$ second_result \u003d array (); // array of results, to calculate the average value of the second option
$ third_result \u003d array (); // array of results, to calculate the average of the third option

// create and fill the array
$ test_array \u003d range (0, $ mass-1); // thanks SelenIT))

/*
$ test_array \u003d array ();
for ($ i \u003d 0; $ i<$mass; $i++)
{
$ test_array \u003d $ i;
}
*/

// loop for calculating average values
for ($ d \u003d 0; $ d<30; $d++) {

// *************** Search with array_search *******************

// Start timing
$ time_start \u003d microtime (1);
// Search
$ key \u003d array_search ($ search, $ test_array, true);
// if found
if ($ key! \u003d\u003d FALSE) // it is necessary! \u003d\u003d and not! \u003d, because the number of the first element is 0
{
echo $ test_array [$ key];
}
$ time_end \u003d microtime (1);
// end time counting

// write to array of values
$ first_result \u003d $ time_end - $ time_start;

// *************** Search in an array with a foreach loop *******************

// Start timing
$ time_start \u003d microtime (1);
// search itself
foreach ($ test_array as $ ta)
{
if ($ ta \u003d\u003d $ search)
{
echo $ ta;
break;
}
}
$ time_end \u003d microtime (1);
// end time counting

// write to array of values
$ second_result \u003d $ time_end - $ time_start;

// *************** Search through an array with a loop while *******************

// Start timing
$ time_start \u003d microtime (1);

// determine the length of the array
$ count \u003d count ($ test_array);
$ j \u003d 0;
// search itself
while ($ j<$count)
{
if ($ test_array [$ j] \u003d\u003d $ search) // if found
{
echo $ test_array [$ j];
break;
}
$ j ++;
}
$ time_end \u003d microtime (1);
// end time counting

// write to array of values
$ third_result \u003d $ time_end - $ time_start;
}

$ srednee1 \u003d array_sum ($ first_result) / count ($ first_result);
$ srednee2 \u003d array_sum ($ second_result) / count ($ second_result);
$ srednee3 \u003d array_sum ($ third_result) / count ($ third_result);

Printf ("first code completed in:% .7f seconds on average", $ srednee1);
printf ("the second code executed in:% .7f seconds on average", $ srednee2);
printf ("third code executed in:% .7f seconds on average", $ srednee3);

// result:
// the first code is executed on average in: 0.0000295 seconds
// the second code is executed on average in: 0.0153386 seconds
// the third code is executed on average in: 0.0226001 seconds

Finding a value in an array is required in almost every PHP application, a script that works with data, for which there are many ways and special functions. Depending on the task and type of search, you should use certain tools, taking into account their features, speed of execution and ease of use. Next, we will get acquainted with PHP functions for finding elements in an array, possible constructions and methods, and also find out which way is the fastest.

Array Search Functions:
array_search - serves to search for a value in an array. If successful, it returns the key of the desired value; if nothing is found, it returns FALSE. Prior to PHP 4.2.0, array_search () returned NULL on failure rather than FALSE.

The syntax for the function is mixed array_search (mixed needle, array haystack [, bool strict]).

foreach (array_expression as $ value)
statement
foreach (array_expression as $ key \u003d\u003e $ value)
statement

An example of using a function with the foreach construction to find an array element, returns TRUE on success

Construction syntax
while (expr)
statement

Returns the key of the array element on success

From the given table of measurements, it can be seen that the function array_search, shows the best results when searching both small and large arrays. In this case, the search time with the help of loops increases significantly depending on the size of the array.