I have been using the array_search () function for searching for values ​​in an array for quite a long time, since I have repeatedly heard and read that it works noticeably faster than searching through an array in a loop, but I did not know how much faster it is. Finally, we got our hands on checking and counting.

I compared the speed of searching in an array using this function with the usual iteration over an array in foreach and while loops. At 10-100 array elements, the difference is imperceptible, and the time is so short that they can be neglected. But for large arrays, the difference turned out to be very significant. With an increase in the size of the array by an order of magnitude, the search time also increased significantly. With a 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 that works with large arrays, replacing the search in a loop with a search using array_search () will not be a "flea optimization" at all.

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

UPD: you need a programmer mindset, you need it too! And mindfulness with memory will not hurt (inspired by break and range :)

Under the habrakat, the script code used to calculate the time:

$ mass = 100000; // the number of values ​​in the array in which we will search
$ search = 50,000; // we will search for this value in the array
$ first_result = array (); // array of results, for calculating 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 of the third option

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

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

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

// *************** Search with array_search *******************

// Start timing
$ 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 time counting

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

// *************** Searching an array with a foreach loop *******************

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

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

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

// Start timing
$ time_start = microtime (1);

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

// write to the 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 executed in:% .7f seconds on average", $ srednee1);
printf ("the second code executed in:% .7f seconds on average", $ srednee2);
printf ("third code executed in:% .7f seconds on average", $ srednee3);

// result:
// the first code is executed on average in: 0.0000295 seconds
// the second code is executed on average in: 0.0153386 seconds
// the third code is executed on average in: 0.0226001 seconds

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

Mechanism of work

PHP's 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 element found is returned and the function is terminated. Therefore, it cannot detect multiple occurrences of the desired value in the array with its help.

If no match is found, the function will return the boolean value FALSE.

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

Examples of using

Example 1. When a multidimensional array is passed to the PHP function array_search (), the result of the operation will be the key of the required 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, the variable $ result1 will be set to "season1", $ result2 will be equal to "season3", and $ result3 will be set to the boolean value FALSE, since the string "april" does not appear in the original array.

Example 2. PHP function array_search () can process a one-dimensional array, considering its keys to be the next numerical indices in order.

The variable $ result will be assigned the value 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 by 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.

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

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, 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 finding elements in an array, possible constructions and methods, and also find out which way is the fastest.

Array Search Functions:
array_search- serves to search for a 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 rather than FALSE.

The syntax for the function is 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 construction to find an array element, returns TRUE on success

Construction syntax
while (expr)
statement

Returns the key of the array element on success

From the given table of measurements, it can be seen that the function array_search, shows the best results when searching in both small and large arrays. In this case, the search time with the help of loops increases significantly depending on the size of the array.

from multidimensional (18)

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

Examples of

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

The function call search_by_uid (100) (uid of the first user) should return 0.

The function call search_by_uid (40489) should return 2.

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

Based on Yakub's excellent answer, here's a more generalized search that will allow you to specify a key (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 is important to know that if you are using === the operator types being compared must be exactly the same, in this example you need to search 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 that you can use one function for multiple array types. Small change, but slightly 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" => "5a9790fd14d48879" = ">" discount_id "=>" 5a9265b914d488548513b122 ",], [" _id "=>" 5a98083614d488191304b6c3 "," discount_amount "=> 15.24," discount_id "=>" 5a92806a14d48858ff5c2 "discount_ed8">], ["_id" => "5a98083614d488191304b6c3" "=> 45.74," discount_id "=>" 5a928ce414d488609e73b443 ",], [" _id "=>" 5a982a4914d48824721eafe55 "," discount_amount "=> 10.26," discount_id "=>" 5a928ce414d4883609e

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 pulled out the param array because I only needed to search for one specific array, but you could easily add it. I wanted to essentially search for more than just a uid.

Also, in my situation, there may be multiple keys to return as a result of searching for 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;)

I later ended up writing this to allow me to look for a different value and 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 specific associative 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 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 to do this, just write this line and you're 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 am doing some simple tests and a form with multiple results seems to be the fastest, even faster than a custom Jakub 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 ( great part) of the search string:

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, a value in an 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 an 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." ")");

Programming is syntax and semantics. The first is determined by the rules of the language, the second - by the developer's experience. With respect to arrays, the developer can subject the syntax to semantics. It is not yet an object, but it is no longer an array in the traditional sense. PHP makes it possible to create arrays from variables of various types, including themselves. An element of an array can be a function, that is, the ability to load an array with a real algorithm, real meaning.

The syntax is stable, but varies from version to version and may not always be upward compatible. Program portability is a well-forgotten achievement of the last century. Semantics develops 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 the rules of the language were not even provided for. Using arrays as an example, this can be understood most simply.

Constructing arrays

PHP arrays have 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

Creation of an array in the process of checking some condition:

$ cSrcLine = "parsed 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 indices from 0 to 12. The same effect can be obtained by previously writing the "future" PHP array into 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 site management systems (SMS) use arrays in a big way. On the one hand, this is good practice, on the other hand, it makes it difficult to apply. Even if the author understands the PHP-array-in-array doctrine, then it should not be overused: 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 the PHP Array in Array sample practice from ZF 2. Not very inspiring at first, but it works and possibly makes the framework a success (example from ZendSkeletonApplication / module / Helloworld / config / module.config.php).

Array is an important data construct during design and development. Its multidimensional version was once popular, but over time, there remains a need for arrays of a maximum of two or three dimensions. This is simpler and more understandable, but 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 in an array in php, it is best to limit yourself to two or three levels. Despite the stability and reliability, PHP makes mistakes when processing syntax. You can put up with this, having a good code editor, accustomed 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 your own ideas for converting semantics into syntax is often an unacceptable luxury. This is a loss of script speed, code readability, ... therefore, ease of coding is always essential.

PHP has a significant drawback: when an ambiguity occurs, the script simply hangs. Not all debuggers deal with contingencies, and a lot depends on the experience and intuition of the developer. The simpler the algorithm, the more accessible the structured information, the more chances to find an error or not to admit it at all.

Typically, when the first arrays appeared, data options were proposed in the form of structures - a clumsy attempt to create something from various data types. The former survived and acquired a new effective syntax, while the latter are history.

Simple and associative arrays

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

It is very effective to create something only when it is needed, in the form in which it was required, and to destroy it when it is no longer needed. Using sensible names as keys (indices), 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"] = "Afanasiev";
$ aAnketa ["age"] = 28;
$ aAnketa ["work"] = "Worker";
$ aAnketa ["active"] = false;
$ aTable = $ aAnketa;

$ sOne. = implode (";", $ aTable). "
"; // second PHP array to string
$ sOne. = $ aTable ["work"]; // access to 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, there are four keys in it: "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 you need a specific employee, then select him by personnel number.

If the organization has divisions, or seasonal workers, or needs to separate out working retirees ... the PHP array in array construct is very handy, but you should never get carried away with dimensionality. Two or three dimensions are the limit for an effective solution.

Keys for working with arrays

If earlier it mattered how everything was arranged, then in recent years the traditions of the binary era, when a programmer wanted to know exactly how the elements of an array were stored, and wanted to have direct access to them, were completely forgotten. There are many character encodings that take up more than one byte in memory. The word "bit" can now be found only in bit search operations, but searching in a PHP array is a separate topic. Element access can 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 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, observing the page and code encoding):

$ 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 loop execution:

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

will receive:

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

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

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

unset ($ aLine); // 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 to a string with one separator, and parse it back into another array using a different separator.

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

It's enough.

Search in an array

PHP contains special search functions and in_array (), however, before deciding to use them, you should consider searching the PHP array yourself.

Any project has concrete constructed arrays, especially when part of the semantics is transferred to 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 meaningfully.

In PHP you can call functions whose names are determined during program execution. A very practical example from the PHPWord library that 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 perform work with real elements of the document.

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 preserve the relationship between keys and values. Sometimes it makes sense to shuffle the array values ​​randomly - shuffle ().

When using PHP functions for sorting, keep in mind that elements can not only have different types, but also not completely 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 the perfect solution yourself, at least during the testing phase of the script, is by manual sorting. She will help to anticipate unforeseen situations.

Inline arrays

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

An array turned into a string opens up new possibilities. For example, the task of finding keywords in the text requires that the found not be 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 variable $ cOne will receive only those values ​​from the original 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, being in the data area, but not in the syntax of the code. Sometimes even a simple PHP task "to print an array to a printer or to a screen" will lead to "krakozyabram", and more often it will just stop the script.

PHP is a loyal language and is tolerant of national encodings, but there are many situations when a completed amount of work has to be done again just because a key value pops up in the right place and at the right time, which will not be 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 foresee everything.

The rule "there is only code in the code, and all the information is at the input, inside, and at the output" will help to avoid unexpected 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.