Contacts

How to check for the presence of a value in the PHP array. PHP: Array_Search - quick search by the PHP array search for an array by value

The search for values \u200b\u200bin the array is required in almost every PHP application, a script for data working with data, for which there are many ways and special functions. Depending on the task and the type of search, you should use certain tools, given their features, the speed of execution and convenience in use. Next, we will get acquainted with PHP functions of searching for elements in array, possible designs and methods, as well as find out what method is the fastest.

Functions for search in the array:
array_Search. - Used to search for values \u200b\u200bin the array. If it is good, it returns the key of the desired value if nothing is found - returns False. Prior to the PHP 4.2.0 version, Array_Search (), with failure, NULL returned, not false.

Mixed Array_Search feature syntax (Mixed Needle, Array Haystack [, Bool Strict]).

foreach (ARRAY_EXPRESSION AS $ Value)
Statement
Foreach (Array_Expression AS $ Key \u003d\u003e $ value)
Statement

An example of using the FEAACH function to search for an array element, returns TRUE when successful

Construction syntax
While (EXPR)
Statement

Returns the case of an array element when successful

From the above table of measurements it can be seen that the function array_Search., shows the best result as when searching for small and large arrays. At the same time, the search time for the set of cycles increases significantly depending on the size of the array.

(PHP 4\u003e \u003d 4.0.5, PHP 5)

array_Search - Searches for this value in the array and returns the appropriate key if good luck

Description

mixed. array_Search. (Mixed Needle, Array Haystack [, BOOL STRICT])

Looking for in the HayStack the value of Needle and returns the key, if so is present in the array, False otherwise.

Comment: If Needle is a string, a register-dependent comparison is made.

Comment: To PHP 4.2.0, array_Search () If possible, returned NULL instead False .

If you pass the value True. as an optional third STRICT parameter, function array_Search () Also check the type Needle in the HayStack array.

If Needle is present in the HayStack more than once, the first key found will be returned. In order to return the keys for all found values, use the function array_keys () With an optional search_value parameter.


Example 1. Example of use array_Search ()

$ Array \u003d Array (0 \u003d\u003e "Blue", 1 \u003d\u003e "Red", 2 \u003d\u003e 0x000000, 3 \u003d\u003e "Green", 4 \u003d\u003e "Red"); $ Key \u003d Array_Search ("Red", $ array ); // $ Key \u003d 1;
$ Key \u003d Array_Search ("Green", $ array); // $ Key \u003d 2; (0x000000 \u003d\u003d 0 \u003d\u003d "Green")
$ Key \u003d Array_Search ("Green", $ Array, True); // $ Key \u003d 3;
?>
Attention

This feature can return as a logical value. False and not relating to the logical type value that is given to False , for example, 0 or "". For more information, refer to the Boulev type section. Use the \u003d\u003d\u003d statement to check the value returned by this function.

One of the main operations when working with arrays is a search for a specific value. For this purpose, the PHP Array_Search () feature. It is capable of processing both one-dimensional and associative collections, returning the key of the desired value if it is found in the array.

Syntax

Formalized description of the Array_Search () function in PHP is as follows:

Mixed Array_Search (Mixed Value, Array $ Collection [, BOOL STRICT])

Input parameters:

  • $ Collection - an array in which the search will be made;
  • value is the desired value of any type;
  • sTRICT is an optional logic flag that establishes a strict comparison mechanism based on types.

Working mechanism

The PHP Array_Search () function alternately compares Value with all the values \u200b\u200bin the Collection array. By default, the comparison is carried out without taking into account the types of operands. This setting can be changed by setting the value of True for the flag. Comparison of strings is carried out with regard to the register.

When the coincidence is detected, the key corresponding to the found element is returned, and the operation of the function stops. Therefore, it is impossible to detect the multiple entry of the desired value into an array.

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

Check the returned result should be using a strict equality operator (\u003d\u003d\u003d). This is important, since the function can return a value that is given to FALSE, for example, 0 or an empty string.

Examples of using

Example 1. When transmitting a multidimensional array to the PHP array_search () function, the result of the work is the key of the desired element.

"Winter", "Season2" \u003d\u003e "Spring", "Season3" \u003d\u003e "Summer", "Season4" \u003d\u003e "Autumn"); $ result1 \u003d Array_Search ("Winter", $ array); $ Result2 \u003d Array_Search ("Summer", $ array); $ result3 \u003d Array_Search ("April", $ array); ? \u003e.

In this example, the $ result1 variable will get "season1", $ result2 will be "season3", and $ result3 will be assigned a boolean value FALSE, since the "April" string does not occur in the source array.

Example 2. The PHP Array_Search () function can also process a one-dimensional array, counting its keys in the order of numerical indexes.

The $ Result variable will be assigned to 1, according to the Hunter element index in the $ array array.

Example 3. Possible error when analyzing the result.

"Washington", 1 \u003d\u003e "adams", 2 \u003d\u003e "jefferson", 3 \u003d\u003e "madison", 4 \u003d\u003e "monroe"); $ result \u003d array_search ("Washington", $ presidents); If (! $ Result) (Echo "G. Washington Was Not The First President of the USA";)?\u003e

So, without checking the resulting 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 detected coincidence is returned.

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

Programming is syntax and semantics. The first is determined by the rules of the language, the second - the experience of the developer. With regard to arrays, the developer can object to the semantics syntax. This is not an object, but no longer an array in a traditional understanding. PHP makes it possible to create arrays from variable different types, including themselves. An element of the array 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 the version to the version and it can not always be compatible even from the bottom up. The portability of programs is well forgotten by the achievement of the last century. Semantics develops and can always be applied not only in any version of any language; It was a tradition to use syntax structures to express that the rules of the language were not even provided. On the example of arrays, this can be understood easily.

Construction of arms

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

public $ anne \u003d array (); // The array is described and does not contain anything

public $ afact \u003d array ("avocado", "peach", "cherry"); // in this array three elements

Creating an array in the process of checking any condition:

$ csrcline \u003d "row of analyzed data";

for ($ i \u003d 0; $ i<13; $i++) {

if (Checkfunc ($ csrcline, $ cuserline) (

$ ARESULT \u003d "YES"; // add to the PHP array

$ ARESULT \u003d "NO";

As a result of the execution of this example, an array of 13 elements will be created, the values \u200b\u200bof which will be only the "Yes" or "NO" strings. The elements will receive indexes from 0 to 12. The same effect can be obtained, after writing a "future" php-array in the string:

$ cfuturearray \u003d "";

for ($ i \u003d 0; $ i<13; $i++) {

$ cuserline \u003d InputUserLine (); // put something

if ($ i\u003e 0) ($ cfuturearray. \u003d "|";)

if (checkfunc ($ csrcline, $ cuserline) ($ cfuturearray. \u003d "YES";

) ELSE ($ cfuturearray. \u003d "No";)

$ ARESULT \u003d Explode ("|", $ cfuturearray);

Multidimensional arrays

Many sites management systems (SMS) use arrays "with a scope". On the one hand, this is a good practice, on the other hand, it makes it difficult to use. Even if the author is clear the doctrine of the "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 time, the creator itself will remember for a long time that he wrote at first:

"view_manager" \u003d\u003e Array (41, "template_path_stack" \u003d\u003e Array (__ dir__. "/../View",),

"Router" \u003d\u003e Array ("Routes" \u003d\u003e Array ("Sayhello" \u003d\u003e Array (

"Type" \u003d\u003e "Zend \\ MVC \\ Router \\ http \\ literal",

"Options" \u003d\u003e Array ("ROUTE" \u003d\u003e "/ SayHello", "defaults" \u003d\u003e array (

"Controller" \u003d\u003e "HelloWorld \\ Controller \\ index", "Action" \u003d\u003e "index",)))))

"Controllers" \u003d\u003e Array ("Invokables" \u003d\u003e Array (

"HelloWorld \\ Controller \\ index" \u003d\u003e "HelloWorld \\ Controller \\ indexController"))

This is a sample of the PHP-array practice in the array "from ZF 2. Not too inspires at first, but it works and, perhaps, makes this framework successful (example from the ZendSkeletonApplication / module / hellogorld / config / module.config.php module).

An array is an important data design during design and development. Its multidimensional option was once popular, but over time the need for arrays of the maximum of two or three dimensions remained. It's easier and clearer, and from the point of view of professionalism when something begins multiplies, it means that something in the formulation of the task or in the code is not true.

Simple, accessible and understandable

Creating an array in an array on PHP, it is best to limit the two-three levels. Despite the stability and reliability of PHP, makes errors in the processing of syntactic structures. You can put up with this, having a good editor code, getting used to accurately consider brackets and commas. However, PHP does not control the data types (this is karma of modern programming) and allows the developer to practice semantic errors.

The rule to control the types of variables or their own ideas for the transformation of semantics into syntax - often incomplete luxury. This is a loss of script speeds, the readability of the code, ... Therefore, simplicity in coding is always essential.

PHP has a significant negative trait: when uncertainty occurs, the script simply hangs. Not all debuggers cope with unforeseen circumstances, and much depends on the experience and intuition of the developer. The easier the algorithm, the more affordable information is structured, the more chances to find an error or not to allow it at all.

It is characteristic that when the first arrays appeared, data options were proposed in the form of structures - a clumsy attempt to create something from different types of data. The first survived and acquired a new effective syntax, the second went downstairs.

Simple and associative arrays

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

Very effectively create something only when it is necessary, in the form in which it took, and destroy when it disappeared the need. Using as keys (indexes) meaningful names, you can get readable designs, meaningful in the context of the current location in the algorithm:

$ aanketa ["Name"] \u003d "Ivanov";
$ aanketa ["AGE"] \u003d 42;
$ aanketa ["work"] \u003d "Director";
$ aanketa ["Active"] \u003d True;
$ ATable \u003d $ aanketa;

$ aanketa ["Name"] \u003d "Petrov";
$ aanketa ["AGE"] \u003d 34;
$ aanketa ["work"] \u003d "manager";
$ aanketa ["Active"] \u003d True;
$ ATable \u003d $ aanketa;

$ aanketa ["Name"] \u003d "Afanasyev";
$ aanketa ["AGE"] \u003d 28;
$ aanketa ["work"] \u003d "worker";
$ aanketa ["Active"] \u003d false;
$ ATable \u003d $ aanketa;

$ sone. \u003d implode (";", $ ATable). "
"; // Second PHP array in the string
$ Sone. \u003d $ ATable ["Work"]; // Appeal to one element of the second array

The result of this example (the first array is usual, the keys in it begin with 0, the second array is associative, in it four keys: "name", "age", "work", "active"):

$ Sone \u003d "Petrov; 34; manager; 1
Manager";

On 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 on the tablet numbers and if a specific employee is needed, then select it on the table number.

If there are divisions in the organization, or there are seasonal workers, or is required to separately allocate working retirees, ... The "PHP-array" design in the array is very convenient, but never be takenlated by dimension. Two or three dimensions - a limit for an effective solution.

Keys for working with arrays

If I used to matter how everything is arranged, in recent years the tradition of the binary era in recent years, when the programmer wanted to know exactly how the elements of the array are stored, and wished to have direct access to them, they were completely forgotten. There are many encodings of characters that occupy not one bytes in memory. The word "bit" can now find anything in the battal search operations, but the search in the PHP array is a separate topic. Access to items may be simple and associative. In the first case, the elements of the array (having any of the types available in PHP) are numbered 0, 1, 2, ... in the second case, the programmer specifies its own index, referred to as "key" to access the desired value.

$ ALINE ["Fruit"] \u003d "Orange"; // here php-key array \u003d "fruit"

or (so that everything is correct with the encoding of the page and code):

$ ALINE \u003d ICONV ("UTF-8", "CP1251", "Orange");

When adding a new value to the array of $ ALINE:

$ ALINE \u003d ICONV ("UTF-8", "CP1251", "PIC");
$ ALINE \u003d ICONV ("UTF-8", "CP1251", "Cucumber");
$ ALINE \u003d ICONV ("UTF-8", "CP1251", "Eggplant");

as a result of the execution of the cycle:

foreach ($ aline as $ ck \u003d\u003e $ CV) (
$ Cone. \u003d $ ck. "\u003d". $ CV. "
";
}

will be obtained:

fruit \u003d Orange
0 \u003d peach
vegetable \u003d cucumber
1 \u003d eggplant

The php-key of an array when adding "peach" and "eggplant" elements is formed sequentially from 0, and when it specifies its value will be equal to this value.

Removal of elements from the array

The easiest way is to process. In this case, for example, as a result of the cycle execution, the source array is viewed, and a new one is formed, into which unnecessary elements are simply not recorded.

You can do it easier. If the last example apply:

unset ($ Aline); // Delete PHP array element

the result will be:

fruit \u003d Orange
vegetable \u003d cucumber
1 \u003d eggplant

The options for manipulating array elements can be constructed a set. For example, using functions: implode () and explode (), you can write a PHP array into a string with one separator, and disassemble back to another array - on another separator.

To simply delete an array on PHP, it is enough to write: Unset ($ Aline);

It's enough.

Search in array

PHP contains special search and in_array () specific functions, but before you decide to use them, you should consider searching in the PHP array on your own.

Any project has specific designed arrays, especially when part of the semantics is transferred to the syntax and is presented with a set of quite specific meaningful keys. This allows you to perform your own search features that can also be referred to.

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

$ Elements \u003d Array ("Text", "Inline", "Textrun", "Link", "PreserveExtEXT", "TextBreak",
"ListItem", "ListItemrun", "Table", "Image", "Object", "FootNote",
"EndNote", "Checkbox", "TextBox", "Field", "Line");

$ functions \u003d array ();

for ($ i \u003d 0; $ i< count($elements); $i++) {
$ Functions [$ i] \u003d "add". $ Elements [$ i];
}

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

Calling for $ Elements function $ functions, you can get the perfect search and a quick result.

Sorting elements

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

Using PHP functions for sorting, you should not forget that the elements may not have different types, but not entirely natural content. First of all, it is necessary to very carefully refer to the sorting of lines containing Russian letters, sorting the date, as well as the numbers that are recorded in different formats.

The best way to write an independent decision, in any case, at the stage of testing the script, is a manual sorting. It will help to provide unforeseen situations.

Line arrays

Thanks to the Implode () and Explode () functions, an array can be easily transformed into the string and get back. This allows you to store data in a compact representation and deploy them to a convenient condition as needed.

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

$ CSRCLINE \u003d "Text Text ListItemrun TextBox ListItem TextBox Check Box Checkbox TextBox Footnote";

$ ASRC \u003d Explode (", $ csrcline);
$ cdstline \u003d "";

for ($ i \u003d 0; $ i< count($aSrc); $i++) {
$ cfind \u003d "[". $ ASRC [$ i]. "]";
if (! is_integer (STRPOS ($ Cdstline, $ CFind))) (
$ cdstline. \u003d $ CFIND;
}
}
$ adst \u003d explode ("] [", $ cdstline);

$ Cone \u003d implode (";, $ ADST);

As a result, the $ Cone variable will only receive the values \u200b\u200bfrom the source line, which are found there for one time: "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 structures. Russian, like all other languages, whose symbols go beyond the limits of A-Z, will not create problems while in the data area, but not in the code syntax. Sometimes even a simple task on PHP "output an array to a printer or on the screen" will lead to "Krakoyarm", and more often will stop the script.

PHP - Loyal language and tolerant refers to national encodings, but there are a lot of situations when the work performed has to be done only because in the right place and at the right time will pop up the key value, to recognize which will not be possible.

PHP syntax and language environment

It should be remembered that the PHP syntax is one, but the designs of this syntax "deal" with other applications, with the operating system, with hardware options. There are many options, it is never possible to foresee.

The rule "in the code is only the code, and at the entrance, inside, and at the output there is every information" will help to avoid unforeseen surprises. The php-value in the array can be "Russian", but the key should be syntactically correct to it not only from the positions of this language, but also from the standpoint of its work.

I have already been using the Array_Search () function for finding values \u200b\u200bin the array, since it has repeatedly heard and read that it works noticeably faster than searching for the array in the cycle, but how faster it did not know. Finally got hands to check and calculate.

Compare the search speed in the array using this function with the usual surfacing of the array in Foreach and While cycles. On 10-100 elements of the array, the difference in invisible and time so little that they can be adeed. But for large arrays, the difference was very significant. With an increase in the size of the array by an order, the search time has increased significantly. With one hundred thousand items, the Foreach speed dropped to 0.013 seconds, and while while - to 0.017, despite the fact that Array_Search () slowed down, but still remained an order of magnitude faster - 0.004 seconds. For a large script running with large arrays, replacing the search in the cycle to search with Array_Search () will not be at all the "flea optimization".

In this regard, I remembered a recent discussion with one of the colleagues at work - about whether the programmer needs to know all these built-in language functions, or a "programmer's programmer's programmer" and general knowledge. Without going out with reasoning about this warehouse of mind, I think that it is still necessary to know the functions, maybe not the entire syntax in the details, but although what functions are there and that they can in general terms.

UPD: Need a programmer warehouse of the mind, also needed! And care with memory will not prevent (inspired Break and Range :)

Under the Habracine Script Code, which calculated the time:

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

// Create and fill an array
$ test_array \u003d Range (0, $ MASS-1); // Thank you selenit))

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

// cycle to count medium values
for ($ d \u003d 0; $ D<30; $d++) {

// *************** Search by Array_Search *******************

// Run a time counting
$ time_start \u003d microtime (1);
// Search
$ Key \u003d Array_Search ($ search, $ test_array, true);
// If found
if ($ Key! \u003d\u003d false) // you need! \u003d\u003d And not! \u003d, because the number of the first element is 0
{
Echo $ Test_Array [$ Key];
}
$ Time_End \u003d microtime (1);
// end count counting

// write in an array of values
$ first_result \u003d $ Time_End - $ Time_Start;

// *************** Search by array with a cycle Foreach *******************

// Run a time counting
$ time_start \u003d microtime (1);
// Search itself
foreach ($ test_array as $ ta)
{
if ($ Ta \u003d\u003d $ SEARCH)
{
Echo $ Ta;
Break;
}
}
$ Time_End \u003d microtime (1);
// end count counting

// write in an array of values
$ Second_Result \u003d $ Time_End - $ Time_STart;

// *************** Search by array with a cycle while *******************

// Run a time counting
$ time_start \u003d microtime (1);

// Determine the length of the array
$ COUNT \u003d COUNT ($ test_array);
$ j \u003d 0;
// Search itself
While ($ J<$count)
{
if ($ test_array [$ j] \u003d\u003d $ search) // if found
{
Echo $ Test_Array [$ J];
Break;
}
$ j ++;
}
$ Time_End \u003d microtime (1);
// end count counting

// write in an array of values
$ Third_Result \u003d $ Time_end - $ Time_STart;
}

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

Printf ("The first code is made on average for:% .7f seconds", $ srednee1);
Printf ("The second code is made on average for:% .7f seconds", $ srednee2);
Printf ("The third code is made on average for:% .7f seconds", $ srednee3);

// Result:
// First code is performed on average for: 0.0000295 seconds
// Second code is made on average for: 0.0153386 seconds
// Third code performed on average for: 0.0226001 seconds



Did you like the article? Share it