Php find element in array value. PHP array_search: Search for a value in an array. PHP syntax and language environment

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, then 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.

from multidimensional (18)

I have modified one of the examples below to describe the array_search function. The searchItemsByKey function returns all values ​​by $key from a multidimensional array (N levels). Perhaps this would be useful for someone. Example:

$arr = array("XXX"=>array("YYY"=> array("AAA"=> array("keyN" =>"value1")), "ZZZ"=> array("BBB"=> array ("keyN" => "value2")) //.....)); $result = searchItemsByKey($arr,"keyN"); print "

"; print_r($result); print " 
"; // OUTPUT Array ( => value1 => value2)

Function code:

Function searchItemsByKey($array, $key) ( $results = array(); if (is_array($array)) ( if (isset($array[$key]) && key($array)==$key) $results = $array[$key]; foreach ($array as $sub_array) $results = array_merge($results, searchItemsByKey($sub_array, $key)); ) return $results; )

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

Examples

Let's assume we have the following two-dimensional array:

$userdb = array(array("uid" => "100", "name" => "Sandra Shush", "pic_square" => "urlof100"), array("uid" => "5465", "name" => "Stefanie Mcmohn", "pic_square" => "urlof100"), array("uid" => "40489", "name" => "Michael", "pic_square" => "urlof40489"));

Calling search_by_uid(100) (the first user's uid) should return 0.

The search_by_uid(40489) function call should return 2 .

I've tried creating loops, but I need faster executable code.

Building on Jakub's excellent answer, here's a more generalized search that will allow you to specify the key (not just for the uid):

Function searcharray($value, $key, $array) ( foreach ($array as $k => $val) ( if ($val[$key] == $value) ( ​​return $k; ) ) return null; )

Usage: $results = searcharray("searchvalue", searchkey, $array);

Function searchForId($id, $array) ( foreach ($array as $key => $val) ( if ($val["uid"] === $id) ( return $key; ) ) return null; )

It will work. You should call it like this:

$id = searchForId("100", $userdb);

It's important to know that if you use === the operator types being compared must be exactly the same, in this example you need to look for string or just use == instead of === .

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

$key = array_search("100", array_column($userdb, "uid"));

Even though this is an old question and there is an accepted answer, I thought I would suggest one change to the accepted answer. So first of all, I agree that the accepted answer here is correct.

Function searchArrayKeyVal($sKey, $id, $array) ( foreach ($array as $key => $val) ( if ($val[$sKey] == $id) ( return $key; ) ) return false; )

Instead, replace the preset "uid" with a parameter in the function, so now calling the code below means you can use one function for multiple array types. Small change, but it's a little different.

// Array Data Of Users $userdb = array (array ("uid" => "100","name" => "Sandra Shush","url" => "urlof100"), array ("uid" => " 5465","name" => "Stefanie Mcmohn","url" => "urlof100"), array ("uid" => "40489","name" => "Michael","url" => "urlof40489 "),); // Obtain The Key Of The Array $arrayKey = searchArrayKeyVal("uid", "100", $userdb); if ($arrayKey!==false) ( echo "Search Result: ", $userdb[$arrayKey]["name"]; ) else ( echo "Search Result can not be found"; )

If(! function_exists("arraySearchMulti"))( function arraySearchMulti($search,$key,$array,$returnKey=false) ( foreach ($array as $k => $val) ( if (isset($val[$ key])) ( if ((string)$val[$key] == (string)$search) ( return ($returnKey ? $k: $val); ) )else( return (is_array($val) ? arraySearchMulti ($search,$key,$val,$returnKey) : null); ) ) return null; ))

you can use this function; https://github.com/serhatozles/ArrayAdvancedSearch

="2""; $Array = array("a" => array("d" => "2"), array("a" => "Example World","b" => "2"), array("c" => "3"), array("d" => "4"),); $Result = ArraySearch($Array,$query,1); echo "

"; print_r($Result); echo "
"; // Output: // Array // (// => Array // (// [a] => Example World // [b] => 2 //) // //)

If the question, i.e.

$a = [ [ "_id" => "5a96933414d48831a41901f2", "discount_amount" => 3.29, "discount_id" => "5a92656a14d488570c2c44a2", ], [ "_id" => "5a9790fd14d48879cf16a9e8", "discount _amount" => 4.53," discount_id" => "5a9265b914d488548513b122", ], [ "_id" => "5a98083614d488191304b6c3", "discount_amount" => 15.24, "discount_id" => "5a92806a14d48858ff5c2ec3", ], [ "_id" => "5a982a4914d48824721eafe3", "discount_amount " => 45.74, "discount_id" => "5a928ce414d488609e73b443", ], [ "_id" => "5a982a4914d48824721eafe55", "discount_amount" => 10.26, "discount_id" => "5a928ce414d488609e73b44 3", ], ];

Function searchForId($id, $array) ( $did=0; $dia=0; foreach ($array as $key => $val) ( if ($val["discount_id"] === $id) ( $ dia +=$val["discount_amount"]; $did++; ) ) if($dia != "") ( echo $dia; var_dump($did); ) return null; ); print_r(searchForId("5a928ce414d488609e73b443",$a));

Try this also

Function search_in_array($srchvalue, $array) ( if (is_array($array) && count($array) > 0) ( $foundkey = array_search($srchvalue, $array); if ($foundkey === FALSE) ( foreach ($array as $key => $value) ( ​​if (is_array($value) && count($value) > 0) ( $foundkey = search_in_array($srchvalue, $value); if ($foundkey != FALSE) return $foundkey; ) ) ) else return $foundkey; ) )

$a = ["x" => ["eee", "ccc"], "b" => ["zzz"]]; $found = null; $search = "eee"; array_walk($a, function ($k, $v) use ($search, &$found) ( if (in_array($search, $k)) ( $found = $v; ) )); var_dump($found);

Here's one liner for the same thing,

$pic_square = $userdb["pic_square"];

Here is my example and please note that this is my first answer. I took out the param array because I only needed to look for one specific array, but you could easily add one. I wanted to essentially search for more than just the uid.

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

/** * @param array multidimensional * @param string value to search for, ie a specific field name like name_first * @param string associative key to find it in, ie field_name * * @return array keys. */ function search_revisions($dataArray, $search_value, $key_to_search) ( // This function will search the revisions for a certain value // related to the associative key you are looking for. $keys = array(); foreach ($dataArray as $key => $cur_value) ( ​​if ($cur_value[$key_to_search] == $search_value) ( ​​$keys = $key; ) ) return $keys; )

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

This second example shows where the value ("Taylor") is found in a specific association key (first_name). AND another value (true) is found in another associative key (used) and returns all matches (Keys in which people named "Taylor" AND are used).

/** * @param array multidimensional * @param string $search_value The value to search for, ie a specific "Taylor" * @param string $key_to_search The associative key to find it in, ie first_name * @param string $other_matching_key The associative key to find in the matches for employed * @param string $other_matching_value The value to find in that matching associative key, ie true * * @return array keys, ie all the people with the first name "Taylor" that are employed. */ function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) ( // This function will search the revisions for a certain value // related to the associative key you are looking for. $ keys = array(); foreach ($dataArray as $key => $cur_value) ( ​​if ($cur_value[$key_to_search] == $search_value) ( ​​if (isset($other_matching_key) && isset($other_matching_value)) ( if ( $cur_value[$other_matching_key] == $other_matching_value) ( ​​$keys = $key; ) ) else ( // I must keep in mind that some searches may have multiple // matches and others would not, so leave it open with no continues . $keys = $key; ) ) ) return $keys; )

Using the function

$data = array(array("cust_group" => 6, "price" => 13.21, "price_qty" => 5), array("cust_group" => 8, "price" => 15.25, "price_qty" => 4), array("cust_group" => 8, "price" => 12.75, "price_qty" => 10)); $findKey = search_revisions($data,"8", "cust_group", "10", "price_qty"); print_r($findKey);

Result

Array ( => 2)

/** * searches a simple as well as multi dimension array * @param type $needle * @param type $haystack * @return boolean */ public static function in_array_multi($needle, $haystack)( $needle = trim($needle ); if(!is_array($haystack)) return False; foreach($haystack as $key=>$value)( if(is_array($value))( if(self::in_array_multi($needle, $value)) return True; else self::in_array_multi($needle, $value); ) else if(trim($value) === trim($needle))(//visibility fix// error_log("$value === $ needle visibility setting to 1 hidden"); return True; ) ) return False; )

If you are using (PHP 5>=5.5.0) you don't need to write your own function for this, just write this line and you'll be done.

If you only want one result:

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

For multiple results

$keys = array_keys(array_column($userdb, "uid"), 40489);

If you have an associative array as stated in the comments, you can do this with:

$keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, "uid")),40489);

If you are using PHP<5.5.0, вы можете использовать этот backport , спасибо ramsey!

Update. I'm doing some simple tests and the multiple results form seems to be the fastest, even faster than Jakub's custom function!

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

$key = array_search("100", array_column($userdb, "uid"));

Expanding on @mayhem's created function, this example would be more of a "fuzzy" search if you just wanted to match part of ( big part) search strings:

Function searchArrayKeyVal($sKey, $id, $array) ( foreach ($array as $key => $val) ( if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) ! == false) ( return $key; ) ) return false; )

For example, the value in the array is Welcome to New York! and you only need the first copy of "New York!"

I had to use the un function, which finds all the elements in the array. So I modified the function performed by Jakub Truneček as follows:

Function search_in_array_r($needle, $array) ( $found = array(); foreach ($array as $key => $val) ( if ($val == $needle) ( array_push($found, $val); ) ) if (count($found) != 0) return $found; else return null; )

$search1 = "demo"; $search2 = "bob"; $arr = array("0" => "hello","1" => "test","2" => "john","3" => array("0" => "martin", "1 " => "bob"),"4" => "demo"); foreach ($arr as $value) ( ​​if (is_array($value)) ( if (in_array($search2, $value)) ( echo "successsfully"; //execute your code ) ) else ( if ($value == $search1) ( echo "success"; ) ) )

If possible, enter the parameter types. But it only works with simple types like int, bool and float.

$unsafe_variable = $_POST["user_id"]; $safe_variable = (int)$unsafe_variable ; mysqli_query($conn, "INSERT INTO table (column) VALUES ("" . $safe_variable . "")");

Searching for a value in an array is required in almost every PHP application and script working with data, for which there are many methods 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 searching elements in an array, possible constructions and methods, and also find out which method is the fastest.

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

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

foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement

An example of using a function with the foreach construct to search for an array element, returning TRUE on success

Construction syntax
while (expr)
statement

Returns the key of an array element on success

From the table of measurements it can be seen that the function array_search, shows the best results both when searching in small and large arrays. At the same time, the search time using loops increases significantly depending on the size of the array.

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 running. 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.

Continuing the topic:
Windows

Xiaomi continues to “close the blind spots” in its assortment, simultaneously releasing screwdrivers, curtains, everything in a row, and then suddenly for some reason it was necessary to “go back” and do...