What this article brings to you is about what the PHP array functions do? PHP Array function application (with code), there is a certain reference value, the need for friends can refer to, I hope to help you.
The PHP array is a very powerful data type, while PHP has built in a series of array-related functions can easily implement the daily development of the function. But I find it seems like a lot of small partners are ignoring the role of built-in functions (like I've written some code about array operations myself and found PHP comes with/(ㄒoㄒ)/~~), leveraging PHP built-in functions can greatly improve development efficiency and operational efficiency (built-in functions are written in C more efficient than PHP Write a lot higher), so this article summarizes some of the common scenarios in the use of PHP built-in function implementation method. Also, if you want to learn more about PHP array functions, it's best to check the PHP manual! Dot I see the official array function manual
Take the specified key name
For some associative arrays, sometimes we just want to take the part of the specified key name, for example, if the array is to ['id' => 1, 'name' => 'zane', 'password' => '123456']
take only the part that contains the ID and name. Paste the code directly below.
<?php$raw = [' id ' = = 1, ' name ' = ' Zane ', ' password ' = ' 123456 '];//own PHP implements function Onlykeys ($raw, $keys) {$new = []; foreach ($raw as $key = + $val) {if (In_array ($key, $keys)) {$new [$key] = $val; }} return $new;} Use PHP built-in functions to implement function Newonlykeys ($array, $keys) {return Array_intersect_key ($array, Array_flip ($keys));} Var_dump (Onlykeys ($raw, [' id ', ' name '));//results [' id ' = ' 1, ' name ' = ' Zane ']var_dump (Newonlykeys ($raw, [' id ', ' name ' ]);//results [' id ' = 1, ' name ' = ' Zane ']
It's obviously a lot of simplicity and there's wood! But array_intersect_key
array_flip
what the hell? Here is a brief introduction to the function of these two functions, first, the function of the function array_flip
is "to swap the keys and values of the array", that is, the key name into a value, the value becomes the key name. The parameters we pass $keys
through this function are [0 => 'id', 1 => 'name']
transformed from ['id' => 0, 'name' => 1]
. The purpose of this is to serve the function array_intersect_key
array_intersect_key
by using the function "to compare the intersection of an array with a key name", that is, to return the value of the first parameter array with the same key name as the other parameter array. This enables the function to take the specified key name ~ (≧▽≦)/~! Of course, to learn more about the functions of these two functions or to check the official PHP manual: Array_flip array_intersect_key
Remove the specified key name
With the previous example to pave the way, this is simple to say, the truth is very similar.
<?php$raw = [' id ' = = 1, ' name ' = ' Zane ', ' password ' + ' 123456 '];//implement function Removekeys with PHP built-in functions ($array, $ Keys) { return Array_diff_key ($array, Array_flip ($keys));} Remove ID Key var_dump (Removekeys ($raw, [' id ', ' password '));//result [' name ' = ' Zane ']
Compared to the previous example, this example simply array_intersect_key
changes the function array_diff_key
to, uh ... I'm sure you can guess. The function "compares the difference set of an array using a key name", just as array_intersect_key
opposed to a function. Official manual: Array_diff_key
Array de-weight
This is believed that everyone has this demand, of course, PHP also built-in array_unique function for everyone to use, the following example:
<?php$input = [' You are ' + 666, ' I am ' = = 233, ' He is ' + 233, ' She is ' + 666]; $result = Array_unique ($in put); Var_dump ($result);//Results [' You is ' + 666, ' I am ' = 233]
Hey, with this function you can solve most of the problems, but sometimes you might think it's not fast enough for the following reasons:
array_unique () sorts the values first as a string, then retains only the first key name encountered for each value, and then ignores all subsequent key names.
Because this function sorts the array first, the speed may not be as expected in some scenarios.
Now we can come up with our black tech array_flip
function, which is well known that the key names of the arrays in PHP are unique, so the values that are duplicated after the key name and value have been swapped are ignored. Imagine that we call two consecutive array_flip
functions is not the equivalent of implementing array_unique
functions of the function? The sample code is as follows:
<?php$input = [' You are ' + 666, ' I am ' = = 233, ' He is ' + 233, ' She is ' + 666]; $result = array_flip (array _flip ($input)); Var_dump ($result);//Results [' she is ' = ' 666, ' he is ' + 233]
Hmm, huh? The result array_unique
is not the same! Why, we can get answers from the official PHP manual:
If the same value occurs more than once, the last key will be its value, and the other keys are discarded.
In general array_unique
, it retains the first key name that appears, array_flip
preserving the last key that appears.
Note : The array_flip
value of the array when used as an array must be able to be a key name (that is, a string type or an integer type), otherwise this value will be ignored.
In addition, we can use this directly if we do not need to preserve the key name array_values(array_flip($input))
.
0X04 Reset Index
When we want to reset an array with an index that is not contiguous, such as an array: [0 => 233, 99 => 666]
we only need to invoke the Array_values function for this array. The following example:
<?php$input = [0] = 233, 666];var_dump (Array_values ($input));//Results [0 = 233, 1 = 66]
It is important to note that the function does not just reset array_values
the numeric index but also removes and resets the string key name. How do you reset the numeric index while preserving the string key name? The answer is the Array_slice function, with the following code example:
<?php$input = [' Hello ' = ' world ', 0 = 233, 666];var_dump (Array_slice ($input, 0));//Results [' hello ' = = ' World ', 0 = 233, 1 = 66]
array_slice
The function is to remove a segment of the array, but it will reorder and reset the numeric index of the array by default, so it can be used to reset the numeric index in the array.
Clear empty values
Hey, sometimes we want to clear an array of empty values such as:,,,,,, and null
false
0
0.0
[]空数组
''空字符串
'0'字符串0
then the Array_filter function can help. The code is as follows:
<?php$input = [' foo ', False,-1, NULL, ', []];var_dump (Array_filter ($input));//Results [0 = ' foo ', 2 = 1]
Why would such a result be pinched? array_filter
is actually "filter the cells in the array with a callback function", its second parameter is actually a callback function, to each member of the array to execute this callback function, if the return value of the callback function to true
retain the member, is false
ignored. Another feature of this function is:
If the callback function is not provided, all entries in the array with FALSE equivalents are removed.
The equivalent of false is the meaning of the value false after conversion to type bool, and a detailed look at the document: Converting to a Boolean type.
Note : If the function is not filled in, callback
0
0.0
'0'字符串0
These potentially meaningful values are deleted. So if you clear the rules differently you also need to write your own callback
functions.
Confirm that the array members are all true
Sometimes we want to make sure that the values in the array are all true
, for example ['read' => true, 'write' => true, 'execute' => true]
, do we need to use a loop to determine this? No,no,no ... Only the ARRAY_PRODUCT function can be implemented. The code is as follows:
<?php$power = [' read ' = True, ' write ' = = True, ' execute ' = true];var_dump (bool) array_product ($power));//Knot Fruit True$power = [' read ' = True, ' write ' = = True, ' execute ' = false];var_dump (bool) array_product ($power));//Results False
Why is it possible to implement this function? The array_product
function originally functions as "the multiplication of all values in an array", and the value of the member is converted to a numeric type when all the members in the multiplier group are evaluated. When the passed argument is an array of a BOOL member, it is known that true
it will be converted to 1 and false
will be converted to 0. Then as long as false
the result of a multiplicative in the array will naturally become 0, and then we will turn the result into a bool
type false
.
Note : Using a array_product
function will evaluate the array member to a numeric type during the calculation, so make sure that you understand the value after the array member is converted to a numeric type, otherwise it will produce unexpected results. Like what:
<?php$power = [' read ' = True, ' write ' = True, ' execute ' = ' true '];var_dump (bool) array_product ($power)); /Result False
The above example is the result 'true'
of being converted to 0 during the calculation. To learn more please click here.
Gets the array before/after the specified key name
What if we want to associate only the part of the array that precedes the specified key name value? With a loop again? Of course we can do it with Array_keys, array_search and array_slice combinations! Paste the following code:
<?php$data = [' first ' = = 1, ' second ' and ' = 2 ', ' third ' = 3];function Beforekey ($array, $key) { $keys = Array_ Keys ($array); $keys = [0 = ' first ', 1 = ' second ', 2 = ' third '] $len = Array_search ($key, $keys); Return Array_slice ($array, 0, $len);} Var_dump (Beforekey ($data, ' first ');//Results []var_dump (Beforekey ($data, ' second '));//Results [' first ' = 1]var_dump ( Beforekey ($data, ' third '));//Results [' first ' = 1, ' second ' + 2]
Thinking analysis, to achieve such a function most of the students should be able to think of array_slice
functions, but this function to take out some of the array is based on the offset (can be understood as the key name in the order of the array, starting from 0) instead of the key name, and the associative array of the key name is a string or is not sequential number, The problem to solve at this point is "how to get the offset of the key name?" "This is a array_keys
function that helps us a lot, its function is" to return all key names in the array or all of the key names, and the returned key an array group is numerically indexed, that is, the index of the returned key an array group is the offset! The original array in the example becomes: [0 => 'first', 1 => 'second', 2 => 'third']
. Then we array_search
can get the offset of the specified key name, because the function is to "search the array for a given value, and if successful, return to the corresponding key name". With an offset we can directly invoke array_slice
the function to achieve the purpose.
The above example understands that it is easy to get the array after the specified key name, which can be changed slightly array_slice
. Direct Sticker Code:
<?php$data = [' first ' = = 1, ' second ' and ' = 2 ', ' third ' = 3];function Afterkey ($array, $key) { $keys = Array_k Eys ($array); $offset = Array_search ($key, $keys); Return Array_slice ($array, $offset + 1);} Var_dump (Afterkey ($data, ' first ');//Results [' second ' = 2, ' third ' = 3]var_dump (Afterkey ($data, ' second '));//Results [' t Hird ' = 3]var_dump (Afterkey ($data, ' third '));//Results []
How do you get an array before or after the specified value? Hey, remember array_search
the role of it, in fact, we just need to call this beforeKey($data, array_search($value, $data))
does not realize it!
Maximum number of repetitions in an array
Knock on the blackboard and draw the key! It is said that this is a question oh. Suppose you have such an array [6, 11, 11, 2, 4, 4, 11, 6, 7, 4, 2, 11, 8]
, how do I get the most repeated values in the array? The key is the Array_count_values function. The instance code is as follows:
<?php$data = [6, one, one, 2, 4, 4, one, 6, 7, 4, 2, one, 8]; $CV = Array_count_values ($data);//$CV = [6 = 2, one by one] 4, 2 = 2, 4 = 3, 7 = 1, 8 = 1]arsort ($CV), $max = key ($CV), Var_dump ($max);//Result 11
array_count_values
function functions are "all values in the statistical array", that is, the values in the original array as the key name of the returned array, the number of times the value appears as the value of the returned array. This allows us to sort the occurrences in descending order using the Arsort function and keep the index associated. Finally, using key to get the key name of the current cell (the first member of the current cell is the default array), the key name is the most repeated value of the original array value.
Summarize
Although PHP provides a lot of and array-related functions, but it is not very convenient to use and all through the function of the call method and no object-oriented implementation, so I recently wrote an open Source Tool class project zane/utils, encapsulated some common methods and support chain call, where the Ary The class implements "get the most repeated values in an array" in just one line, as follows:
$data = [6, one, one, 2, 4, 4, one, 6, 7, 4, 2, one, 8]; $max = ary::new ($data)->countvalues ()->maxkey (); Var_dump ($max); /result 1