Php search in associative array by value. PHP: array_search - quick array search


I have been using the array_search() function for quite a long time to search for values ​​in an array, since I have repeatedly heard and read that it works noticeably faster than searching through an array in a loop, but I didn’t know how much faster it is. Finally got around to checking and counting it myself.

I compared the speed of searching through an array using this function with the usual search through an array in foreach and while loops. On 10-100 array elements the difference is unnoticeable and the time is so short that it can be neglected. But for large arrays the difference turned out to be quite significant. As the array size increased by an order of magnitude, the search time also increased significantly. With one 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 working with large arrays, replacing a search in a loop with a search using array_search() will not be a “flea optimization” at all.

In this regard, I remembered a recent discussion with one of my colleagues at work about whether a programmer needs to know all these built-in language functions, or whether a “programmer’s mindset” and general knowledge are 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 there are and what they can do in general terms.

UPD: you need a programmer's mindset, too! And being careful with your memory won’t hurt (inspired by break and range:)

Below the hack is the script code that was used to calculate the time:

$mass=100000; // number of values ​​in the array in which we will search
$search=50000; // we will look for this value in the array
$first_result=array(); // array of results to calculate the average value of the first option
$second_result=array(); // array of results to calculate the average value of the second option
$third_result=array(); // array of results to calculate the average value of the third option

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

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

// loop to calculate average values
for ($d=0; $d<30; $d++) {

//*************** Search using array_search *******************

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

// write to an array of values
$first_result= $time_end - $time_start;

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

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

// write to an array of values
$second_result= $time_end - $time_start;

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

// Start counting time
$time_start = microtime(1);

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

// write to an array of values
$third_result= $time_end - $time_start;
}

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

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

// result:
// first code completed in average: 0.0000295 seconds
// second code completed in average: 0.0153386 seconds
// third code completed in average: 0.0226001 seconds

Often when writing code, you need to check whether a particular element value exists in an array. Today we will look at several functions with which you can do this.

Checking the presence of an element value in an array can be used to solve various programming problems.

We can get various arrays from our database and check for the presence of a particular value in it. The desired value can also be transmitted from the user of our script when, for example, he is looking for something. Based on the results of such a search, you can perform certain actions. It all depends on the specific task at hand, however, the algorithms for searching for a value in an array will be the same.

Today we will look at them.

Checking the presence of a value in an array. in_array() function

Function in_array() will allow us to check the presence of any value in the array.

If the result of its work is successful and the desired element is found in the array, then the function will return true, that is, “the truth.”

The function takes 2 required parameters:<Что ищем>And<Где ищем>.

It can also take one more optional parameter:<Тип данных>. If this third optional parameter is set to true, then the data type is also checked. That is, ‘2’ and 2 will not be the same thing. In the first case it is a string, in the second it is a number. And then the whole function in_array() will not return a value true.

You also need to remember that the function performs case-sensitive comparisons.

Let's look at how this function works using a simple example.
We need some kind of array. Using the function, we will check for the presence of a value in the array and display a specific message on the screen.

After execution, the function will display the message “Yes”, since the element “Marina” is present in our array.

Change the first parameter in the function to some non-existent element, and you will see the message “No”.

Checking the presence of a value in an array. array_search() function

There is another search function array_search(), which, unlike the previous one, will return the key of the found element. This, in turn, can be useful if we are working with an associative array.

The function takes the same parameters as the previous one. In this case, the third parameter is also optional.

Let's see how it can be used when working with an associative array.

"october","money"=>200,"name"=>"Mila"); $key = array_search("Mila",$Mass1); if($key) echo $key; ?>

In this case, we will see “name” on the screen, that is, the key to the desired element with the value “Mila”.

These two functions are very similar and essentially differ only in the return value.

Finding a value in a multidimensional array

But what if we are working with a multidimensional array? After all, its elements will be other arrays.

Here the algorithms we have already discussed will not work.

It's actually not that complicated, you just need to complicate the whole mechanism a little and use a loop, for example, foreach(), which works great with arrays.

Let's say we have a multidimensional array. Its immediate values ​​are other arrays that may contain the element's desired value.

All you have to do is loop through the elements of the original array foreach(). Each element of this array will be parsed into a key ($key) and a value ($value).

The value will be each of the arrays located inside the main multidimensional array. We will work with these values, searching in each internal array for the desired element value.

If found, we will display a message stating that such an element exists, and if not, we will display another message that such an element does not exist.

Let's see all this with example code:

"anna","id"=>234); $Mass2 = array("name"=>"anton","id"=>24); $Mass2 = array("name"=>"ivan","id"=>007); foreach($Mass2 as $key => $value) ( ​​$name .= in_array("ivan",$value); ) if($name) echo "OK! Element here!"; else echo "No have element!"; ?>

As you can see, first we declare the multidimensional array itself.

Moreover, here you must write not just an equal sign, but “.=”.

This is done so that the $name variable is not overwritten at each iteration, but is supplemented. After all, if at the first iteration an element is found and the value “true” is written to the $name variable, but at the second iteration (that is, in the second internal array) the desired value of the element is not present, then the value of the $name variable will simply be overwritten, and in the end we simply will not we get the correct result.

As you understand, the result of this code will be the message “OK! Element is here!

Try to change the element you are looking for to a non-existent one and you will see the message “No have element!”

Of course, when a certain element is found or not found, we can not just display messages, but do some other actions. It all depends on what you need to do. For example, if the desired value is in the array, you can give the user some specific information, etc.

That's all for today! I hope the lesson was clear and useful! Try writing similar code yourself to fully understand everything.

And I'm waiting for your comments.

Share the lesson with your friends using social buttons. networks located below. And also subscribe to blog updates. We have already collected a fairly good archive of useful materials, and they will only be replenished!

I wish you successful programming!

Anna Kotelnikova was with you!

One of the main operations when working with arrays is searching for a specific value. The PHP array_search() function is designed for this. It is capable of processing both one-dimensional and associative collections, returning the key of the searched value if it is 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 - the desired value of any type;
  • strict is an optional boolean flag that sets a strict type-aware comparison mechanism.

Mechanism of operation

The PHP array_search() function compares value one by one with all the values ​​in 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 found element is returned and the function stops working. Therefore, it cannot be used to detect multiple occurrences of the desired value in an array.

If no matches are found, the function will return the boolean value FALSE.

You should check the returned result using the strict equality operator (===). This is important because the function may return a value that is cast to FALSE, such as 0 or the empty string.

Examples of using

Example 1. When passing a multidimensional array to the PHP array_search() function, the result of the work will be the key of the searched element.

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

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

Example 2. The PHP array_search() function can also process a one-dimensional array, considering its keys as the following numeric indices.

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

Example 3. Possible error when analyzing the result.

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

So, without checking the result with 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.

Even though the value you are looking for occurs three times in the array, the function will only return the first result found - 0. To find multiple matches, it is recommended to use the PHP array_keys() function.

(PHP 4 >= 4.0.5, PHP 5)

array_search -- Searches for a given value in an array and returns the corresponding key if successful

Description

mixed array_search(mixed needle, array haystack [, bool strict])

Looks up the haystack for the needle value and returns the key if it is present in the array, FALSE otherwise.

Comment: If needle is a string, a case-sensitive comparison is performed.

Comment: Up to PHP 4.2.0, array_search() returned if unsuccessful NULL instead of FALSE .

If you pass the value TRUE as an optional third parameter to strict , the function array_search() will also check the type of needle in the haystack array.

If needle is present in the haystack more than once, the first key found will be returned. To return the keys for all found values, use the function array_keys() with an optional search_value parameter.


Example 1: Usage example array_search()

$array = array(0 => "blue" , ​​1 => "red" , 2 => 0x000000 , 3 => "green" , 4 => "red" );$key = array_search ("red" , $array ); // $key = 1;
$key = array_search("green" , $array ); // $key = 2; (0x000000 == 0 == "green")
$key = array_search ("green" , $array , true ); // $key = 3;
?>
Attention

This function can return as a boolean value FALSE, a non-Boolean value that is cast to FALSE, for example 0 or "". For more information, see the Boolean type section. Use the === operator to check the value returned by this function.







2024 gtavrl.ru.