• Php search in array for part of value. PHP array_search: Searching for a value in an array. Removing elements from an array

    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 respect to arrays, the developer can subtly load the syntax with semantics. It is not yet an object, but it is no longer an array in the traditional sense. PHP allows you to create arrays from variables of various types, including yourself. 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 the bottom up. 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 things that were not even provided for by the rules of the language. Using the example of arrays, this can be understood most simply.

    Array construction

    An array in PHP has a convenient syntax and functionality. This one can be described in advance, but it's often convenient to create arrays on the fly as needed.

    public $aNone = array(); // 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 = "line of parsed data";

    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 be indexed from 0 to 12. The same effect can be obtained by first writing the "future" PHP array to a string:

    $cFutureArray = "";

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

    $cUserLine = inputUserLine(); // input 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 a good practice, on the other hand, it makes it difficult to apply. Even if the author understands the doctrine of "PHP-array in an array", then it should not be abused: not only the developer will have to get used to 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 ZF 2's PHP array-in-array sample practice. Not very inspiring at first, but it works and probably makes this framework successful (example from ZendSkeletonApplication/module/Helloworld/config/module.config.php module).

    An array is an important data construct during design and development. Its multidimensional variant was once popular, but over time, the need for arrays of a maximum of two or three dimensions remained. It’s easier and clearer this way, and from the point of view of professionalism, 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 in the processing of syntactic constructs. You can put up with this if you have a good code editor, and get used to accurately counting brackets 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 one's own ideas of 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 an ambiguity occurs, the script simply hangs. Not all debuggers 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 more likely it is to find an error or not make it at all.

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

    Simple and associative arrays

    A two-dimensional array entry is another pair of brackets "[" and "]", for example: $aSrcData refers to an element of the array included in the $aSrcData array. In PHP there is no requirement to declare data in advance. Any declared information can always be checked for existence.

    It is very efficient to create something only when it is needed, in the form in which it is needed, and destroy it when it is no longer needed. Using meaningful names as keys (indexes), you can get readable constructions that make sense 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"] = "Afanasiev";
    $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";

    In this simple example, you can see how the created questionnaire can be applied to all employees. You can create an array of employees with indexes by personnel numbers and, if a specific employee is needed, then select him by personnel number.

    If the organization has subdivisions, or there are seasonal workers, or you need to separate working retirees, ... the "PHP-array-in-array" construction 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 works, then in the last years of the binary era, when the programmer wanted to know exactly how the elements of the array were stored and wanted to have direct access to them, they were completely forgotten. Many character encodings have appeared that occupy far more than one byte in memory. The word "bit" can now only be found in bit search operations, but searching in a PHP array is a separate issue. 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 the "key" to access the desired value.

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

    or (so that everything is correct, respecting the encoding of the page 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 the loop:

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

    will receive:

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

    PHP-key of the array when adding the elements "peach" and "eggplant" is formed sequentially from 0, and when you specify 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 the execution of the loop, the original array is scanned and a new one is formed, in which unnecessary elements are simply not written.

    You can do it easier. If applied to the last example:

    unset($line); // remove element from PHP array

    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 the entire array in PHP, just write: unset($aLine);

    It's enough.

    Array search

    PHP provides special lookup and in_array() functions, but before deciding to use them, you should consider doing your own PHP array lookup.

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

    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 elements of the document.

    By calling the $functions function on $elements, you can get a perfect lookup and a fast result.

    Sorting elements

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

    When using PHP functions for sorting, one should not forget that elements can have not only a different type, but also not quite 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 your own perfect solution, at least in the testing phase of the script, is to manually sort. It will help to anticipate unforeseen situations.

    String arrays

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

    An array converted to a string opens up new possibilities. For example, the task of searching for keywords in the 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 occur there once: "Text; ListItemRun; TextBox; ListItem; Check; Box; CheckBox; Footnote".

    Russian language in keys and values

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

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

    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 foresee everything.

    The rule “there is only code in the code, and there is any information at the input, inside, and at the output” will help to avoid unforeseen surprises. The PHP value in the 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 environment.

    Finding a value in an array is required in almost every PHP application, script that works with data, for which there are many ways and special functions. Depending on the task and type of search, one or another tool should be used, taking into account their features, speed of execution and ease of use. Next, we will get acquainted with the PHP functions for finding 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— serves for search of 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, not FALSE.

    Syntax for 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 a foreach construct to find an array element, returns TRUE on success

    Construction syntax
    while (expr)
    statement

    Returns the key of an array element on success

    From the above table of measurements it can be seen that the function array_search, shows the best result 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.

    (PHP 4 >= 4.0.5, PHP 5)

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

    Description

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

    Searches the haystack for needle and returns the key, if any, in the array, FALSE otherwise.

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

    Comment: Before PHP 4.2.0, array_search() returned on failure NULL instead of FALSE .

    If you pass a 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 more than once in the haystack, the first key found will be returned. To return the keys for all found values, use the function array_keys() with optional parameter search_value .


    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 FALSE, and a non-boolean value that is cast to FALSE, for example, 0 or "". See Boolean type for more information. Use the === operator to test the value returned by this function.

    from multidimensional (18)

    I modified one of the examples below the description of the array_search function. The searchItemsByKey function returns all values ​​by $key from a multidimensional array (N levels). Perhaps this would be helpful to 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 search for the uid and get the key from the array.

    Examples

    Suppose 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"));

    A call to search_by_uid(100) (the uid of the first user) should return 0 .

    The search_by_uid(40489) function call should return 2 .

    I have tried creating loops, but I need faster executable code.

    Based on Jakub's excellent answer, here is a more generalized lookup that will allow the key to be specified (not just for 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 angoru. 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 the same function for multiple array types. A 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" => "5a928ce414d488609e73b 443", ], ];

    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,

    $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 it. I wanted to essentially look for more than just the uid.

    Also, in my situation, there may be multiple keys to return in the search result with 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 look up a different value and an associative key. Therefore, my first example allows you to search for a value in any particular associative key and return all matches.

    This second example shows where the value ("Taylor") is found in a particular association key (first_name). AND another value (true) is found in another association key (used) and returns all matches (Keys where 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; )

    Function use

    $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 setting visibility 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 are 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 mentioned in the comments, you can do it 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 result 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 is more of a "fuzzy" search if you just want to match the ( 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 need the first copy of only "New York!".

    I had to use the un function which finds all the elements in the array. Therefore, I changed the function performed by Jakub Trunechk 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 . "")");

    One of the basic 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 lookup 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 - array to be searched;
    • value - the desired value of any type;
    • strict is an optional boolean flag that sets a strict type-aware comparison mechanism.

    Working mechanism

    The PHP array_search() function compares value in turn with all the values ​​in the collection array. By default, the comparison is carried out without taking into account the types of the operands. This setting can be changed by setting the strict flag to TRUE. String comparison is case-sensitive.

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

    If no match is 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 evaluates to FALSE, such as 0 or an 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 element being searched for.

    "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 occur in the original array.

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

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

    Example 3. Possible error in the analysis of 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 searched value occurs three times in the array, the function will only return the first result found - 0. To search for multiple matches, it is recommended to use the PHP array_keys() function.