Php find element in array by value. PHP array_search: searching for a value in an array


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!

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

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.

Programming is about syntax and semantics. The first is determined by the rules of the language, the second by the experience of the developer. With regard to arrays, the developer can specifically load the syntax with semantics. This is not yet an object, but it is no longer an array in the traditional sense. PHP gives you the ability to create arrays of variables of various types, including themselves. An array element can be a function, that is, the ability to load the array with a real algorithm, real meaning.

The syntax is stable, but changes from version to version and may not always be compatible even from bottom to top. Program portability is a well-forgotten achievement of the last century. Semantics is evolving and can always be applied not only in any version of any language; It has become a tradition to use syntactic constructions to express what was not even provided for by the rules of the language. This can be most easily understood using the example of arrays.

Constructing Arrays

Array in PHP has convenient syntax and functionality. This can be described in advance, but it is often convenient to create arrays on the fly as needed.

public $aNone = array(); // the array is described and contains nothing

public $aFact = array("avocado", "peach", "cherry"); // this array has three elements

Creating an array while checking a condition:

$cSrcLine = "analyzed data line";

for ($i=0; $i<13; $i++) {

if (checkFunc($cSrcLine, $cUserLine) (

$aResult = "Yes"; // add to PHP array

$aResult = "No";

As a result of executing this example, an array of 13 elements will be created, the values ​​of which will be only the strings “Yes” or “No”. The elements will receive indexes from 0 to 12. The same effect can be achieved by first writing the “future” PHP array into a string:

$cFutureArray = "";

for ($i=0; $i<13; $i++) {

$cUserLine = inputUserLine(); // enter something

if ($i > 0) ( $cFutureArray .= "|"; )

if (checkFunc($cSrcLine, $cUserLine) ( $cFutureArray .= "Yes";

) else ( $cFutureArray .= "No"; )

$aResult = explode("|", $cFutureArray);

Multidimensional arrays

Many content management systems (CMS) use arrays in a big way. On the one hand, this is good practice, on the other hand, it makes it difficult to use. Even if the author understands the “PHP array within an array” doctrine, he should not abuse it: not only the developer will have to get used to the complex notation. Often, after a while, the creator himself will remember for a long time what he wrote at first:

"view_manager" => array(41, "template_path_stack" => array(__DIR__ . "/../view",),

"router" => array("routes" => array("sayhello" => array(

"type" => "Zend\Mvc\Router\Http\Literal",

"options" => array("route" => "/sayhello", "defaults" => array(

"controller" => "Helloworld\Controller\Index", "action" => "index",))))),

"controllers" => array("invokables" => array(

"Helloworld\Controller\Index" => "Helloworld\Controller\IndexController"))

This is an example of the "PHP array within an array" practice from ZF 2. Not very inspiring at first, but it works and arguably makes this framework successful (example from ZendSkeletonApplication/module/Helloworld/config/module.config.php).

An array is an important data construct during design and development. Its multidimensional version was once popular, but over time there remained a need for arrays of a maximum of two or three dimensions. It’s simpler and clearer this way, and from a professional point of view, when something starts to multiply, it means that something is wrong in the problem statement or in the code.

Simple, accessible and understandable

When creating an array within an array in PHP, it is best to limit yourself to two or three levels. Despite the stability and reliability of PHP, it makes errors when processing syntactic structures. You can put up with this if you have a good code editor and get used to accurately counting parentheses and commas. However, PHP does not control data types (this is the karma of modern programming) and allows the developer to practice semantic errors.

The rule to control the types of variables or your own ideas for turning semantics into syntax is often an unaffordable luxury. This is a loss of script speed, code readability, ... because simplicity in coding is always essential.

PHP has a significant negative feature: when uncertainty arises, the script simply freezes. Not all debuggers can handle unforeseen circumstances, and a lot depends on the experience and intuition of the developer. The simpler the algorithm, the more accessible the information is structured, the greater the chances of finding an error or preventing it altogether.

It is characteristic that when the first arrays appeared, variants of data were proposed in the form of structures - a clumsy attempt to create something from different data types. The former survived and acquired a new effective syntax, while the latter became history.

Simple and associative arrays

Notation for a two-dimensional array is another pair of brackets "[" and "]", for example: $aSrcData means accessing an array element included in the $aSrcData array. There is no requirement to declare data in advance in PHP. Any stated information can always be verified for existence.

It is very effective to create something only when it is needed, in the form in which it was required, and destroy it when the need for it has disappeared. Using meaningful names as keys (indexes), you can get readable constructs that are meaningful in the context of the current place in the algorithm:

$aAnketa["name"] = "Ivanov";
$aAnketa["age"] = 42;
$aAnketa["work"] = "Director";
$aAnketa["active"] = true;
$aTable = $aAnketa;

$aAnketa["name"] = "Petrov";
$aAnketa["age"] = 34;
$aAnketa["work"] = "Manager";
$aAnketa["active"] = true;
$aTable = $aAnketa;

$aAnketa["name"] = "Afanasyev";
$aAnketa["age"] = 28;
$aAnketa["work"] = "Worker";
$aAnketa["active"] = false;
$aTable = $aAnketa;

$sOne .= implode ("; ", $aTable) . "
"; // second PHP array into a string
$sOne .= $aTable["work"]; // accessing one element of the second array

The result of this example (the first array is normal, the keys in it start from 0, the second array is associative, it has four keys: "name", "age", "work", "active"):

$sOne = "Petrov; 34; Manager; 1
Manager";

This simple example shows how a created questionnaire can be applied to all employees. You can create an array of employees with indexes by personnel numbers and, if you need a specific employee, select him by personnel number.

If the organization has divisions, or there are seasonal workers, or you need to separately identify working pensioners, ... the “PHP array in an array” design is very convenient, but you should never get carried away with the dimension. Two or three dimensions is the limit for an effective solution.

Keys for working with arrays

If before it mattered how everything was arranged, then in recent years the traditions of the binary era, when the programmer wanted to know how exactly the elements of an array were stored and wanted to have direct access to them, were completely forgotten. Many character encodings have appeared that take up more than one byte in memory. The word "bit" can now only be found in bit search operations, but searching a PHP array is a separate topic. Access to elements can be simple and associative. In the first case, the array elements (having any of the types available in PHP) are numbered 0, 1, 2, ... In the second case, the programmer specifies his own index, often called a “key,” to access the desired value.

$aLine["fruit"] = "orange"; // here PHP array key = "fruit"

or (so that everything is correct, respecting the page encoding and code):

$aLine = iconv("UTF-8", "CP1251", "orange");

When adding a new value to the $aLine array:

$aLine = iconv("UTF-8", "CP1251", "peach");
$aLine = iconv("UTF-8", "CP1251", "cucumber");
$aLine = iconv("UTF-8", "CP1251", "eggplant");

as a result of executing the loop:

foreach ($aLine as $ck => $cv) (
$cOne .= $ck . "=" . $cv . "
";
}

will be received:

fruit=orange
0=peach
vegetable=cucumber
1=eggplant

The PHP array key when adding the elements “peach” and “eggplant” is formed sequentially from 0, and when specifying its value it will be equal to this value.

Removing elements from an array

The easiest way is during its processing. In this case, for example, as a result of executing a loop, the original array is scanned and a new one is formed, into which unnecessary elements are simply not written.

It could be easier. If we apply to the last example:

unset($aLine); // remove array element PHP

then the result will be:

fruit=orange
vegetable=cucumber
1=eggplant

There are many options for manipulating array elements. For example, using the functions: implode() and explode(), you can write a PHP array into a string with one delimiter, and parse it back into another array using a different delimiter.

To simply delete an entire array in PHP, just write: unset($aLine);

It's enough.

Search in an array

PHP contains special search and in_array() functions, but before you decide to use them, you should consider doing PHP array searches yourself.

Any project has specific constructed arrays, especially when part of the semantics is transferred to the syntax and is represented by a set of very specific meaningful keys. This allows you to perform your own search functions, which can also be labeled in a meaningful way.

In PHP, you can call functions whose name is determined during program execution. A very practical example from the PHPWord library, which allows you to read and create MS Word documents:

$elements = array("Text", "Inline", "TextRun", "Link", "PreserveText", "TextBreak",
"ListItem", "ListItemRun", "Table", "Image", "Object", "Footnote",
"Endnote", "CheckBox", "TextBox", "Field", "Line");

$functions = array();

for ($i = 0; $i< count($elements); $i++) {
$functions[$i] = "add" . $elements[$i];
}

As a result, the $functions array will receive the values ​​of the $elements array, that is, the names of real functions that work with real document elements.

By calling $functions on $elements, you can get a perfect search and fast results.

Sorting items

The task of sorting data is important and PHP offers several functions for this: sort(), rsort(), asort(), ksort(), ... Ascending and descending elements, the second two functions store the relationships between keys and values. Sometimes it makes sense to shuffle the array values ​​randomly - shuffle().

When using PHP functions for sorting, you should not forget that elements can not only have different types, but also not entirely natural content. First of all, you need to be very careful about sorting strings containing Russian letters, sorting dates, as well as numbers that are written in different formats.

The best way to write an ideal solution yourself, at least at the stage of testing the script, is manual sorting. It will help anticipate unforeseen situations.

String Arrays

Thanks to the implode() and explode() functions, an array can be easily transformed into a string and returned back. This allows you to store data in a compact representation and expand it into a convenient state as needed.

An array converted to a string opens up new possibilities. For example, the task of searching for keywords in a text requires that what is found is not added again.

$cSrcLine = "Text Text ListItemRun TextBox ListItem TextBox Check Box CheckBox TextBox Footnote";

$aSrc = explode(" ", $cSrcLine);
$cDstLine = "";

for ($i=0; $i< count($aSrc); $i++) {
$cFind = "[" . $aSrc[$i] . "]";
if (! is_integer(strpos($cDstLine, $cFind))) (
$cDstLine .= $cFind;
}
}
$aDst = explode("][", $cDstLine);

$cOne = implode("; ", $aDst);

As a result, the $cOne variable will receive only those values ​​from the source string that appear there once: "Text; ListItemRun; TextBox; ListItem; Check; Box; CheckBox; Footnote".

Russian language in keys and meanings

It is not recommended to use anything related to national encodings in syntactic structures. Russian, like all other languages ​​whose characters extend beyond a-z, will not create problems, being in the data region, but not in the code syntax. Sometimes even a simple task in PHP “output an array to the printer or to the screen” will lead to “crazy bugs”, and more often the script will simply stop.

PHP is a loyal language and is tolerant of national encodings, but there are many situations when the completed amount of work has to be done again only because a key value pops up in the right place and at the right time, which is not possible to recognize.

PHP syntax and language environment

It should be remembered that PHP syntax is one thing, but the constructs of this syntax “deal” with other applications, with the operating system, with hardware options. There are many options, it is never possible to provide for everything.

The rule “there is only code in the code, but there is all sorts of information at the input, inside, and output” will help avoid unforeseen surprises. A PHP value in an array can be “Russian”, but the key to it must be syntactically correct not only from the standpoint of the given language, but also from the standpoint of its operating environment.







2024 gtavrl.ru.