0 x00 preface

PHP arrays are a powerful data type, and PHP has a series of built-in array-related functions that make it easy to implement everyday development functions. But I have found that many others seem to be ignoring the value of built-in functions (I myself wrote some array operations and discovered THAT PHP came with /), and that leveraging them (those written in C were far more efficient than those written in PHP) can be vastly more effective. So this article summarizes some implementations of PHP’s built-in functions in common scenarios. In addition, if you want to learn more about PHP array functions better consult the PHP manual! Click me to see the official array function manual

0x01 Takes the specified key name

[‘id’ => 1, ‘name’ => ‘zane’, ‘password’ => ‘123456’] The code is posted directly below.

<? php $raw = ['id' => 1, 'name' => 'zane', 'password' => '123456']; Function onlyKeys($raw, $keys) {$new = []; foreach ($raw as $key => $val) { if (in_array($key, $keys)) { $new[$key] = $val; } } return $new; 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'])); // Result ['id' => 1, 'name' => 'zane'] copies codeCopy the code

It’s obviously a lot simpler. But what are array_intersect_key and array_flip? The first function is array_flip, which swaps the key and value of an array. That is, the key names become values, and the values become keys. The $keys argument we passed is converted from [0 => ‘id’, 1 => ‘name’] to [‘id’ => 0, ‘name’ => 1]. The purpose of this is to serve the array_Intersect_key function, which “calculates the intersection of arrays using key name comparison”, that is, returns the value of the first parameter array with the same key name as the other parameter arrays. This implements the function of fetching the specified key name ~(≧▽≦)/~! For details on the functions of these two functions, please refer to the official PHP manual array_flip array_Intersect_key

0x02 Removes the specified key name

With the last example as a foundation, this is a brief introduction, the principle is more or less the same.

<? php $raw = ['id' => 1, 'name' => 'zane', 'password' => '123456']; Function removeKeys($array, $keys) {return array_diff_key($array, array_flip); Var_dump ($raw, ['id', 'password']); // Result ['name' => 'zane'] replicates codeCopy the code

Compared to the previous example, this example simply changes the array_intersect_key function to array_diff_key, HMM… As you can guess, the function “calculates the difference set of arrays by comparing key names” is the opposite of array_intersect_key. Official manual: array_DIFF_key

0x03 Array deduplication

PHP also has a built-in array_unique function for you to use, as in the following example:

<? php $input = ['you are' => 666, 'i am' => 233, 'he is' => 233, 'she is' => 666]; $result = array_unique($input); var_dump($result); // result ['you are' => 666, 'I am' => 233] copy codeCopy the code

Hey, using this function will do most things, but sometimes you might find it not fast enough for the following reasons:

Array_unique () sorts the values as strings, keeps only the first encountered key name for each value, and then ignores all subsequent key names.

Because this function sorts the array first, the speed may not be as fast as expected in some scenarios.

Now we can use our hack array_flip function. As we know, array keys are unique in PHP, so duplicate values are ignored after swapping key names and values. If we call array_flip twice in a row, would array_unique function be implemented? Example 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); // Result ['she is' => 666, 'he is' => 233] copy codeCopy the code

Uh huh? ! The result is not the same as array_unique! Why, we can find out from the official PHP manual:

If the same value occurs more than once, the last key name is used as its value, and other keys are discarded.

In general, array_unique keeps the first occurrence of the key, and array_flip keeps the last occurrence of the key.

Note: When array_flip is used as an array for deleveraging, the value of the array must be able to be used as a key name (that is, of type string or integer), otherwise the value will be ignored.

In addition, we can use array_values(array_flip($input)) directly if we don’t need to keep the key name.

0x04 Resets an index

When we want to reset an array whose indexes are not contiguous, such as array: [0 => 233, 99 => 666], we simply call array_values. The following cases:

<? php $input = [0 => 233, 99 => 666]; var_dump(array_values($input)); // Results [0 => 233, 1 => 66] copy codeCopy the code

Note that the array_values function does not just reset numeric indexes but also removes and resets string keys as well. So how do you reset the numeric index while preserving the string key? The answer is the array_slice function, as shown in the following code:

<? php $input = ['hello' => 'world', 0 => 233, 99 => 666]; var_dump(array_slice($input, 0)); / / results [' hello '= >' world ', 0 = > 233, 66] 1 = > duplicate codeCopy the code

The array_slice function fetches a segment of an array, but it reorders and resets the array’s numeric index by default, so you can use it to reset the array’s numeric index.

0x05 Clears the null value

Hey, sometimes we want to clear an array of null values such as null, false, 0, 0.0, [] empty array, ” empty string, ” 0′ string 0, and array_filter is a great help. The code is as follows:

<? php $input = ['foo', false, -1, null, '', []]; var_dump(array_filter($input)); // Result [0 => 'foo', 2 => -1] copies the codeCopy the code

Why would there be such a result pinch? Array_filter’s second argument is a callback function that executes on each member of the array. If the callback returns true, the member is kept, and if it returns false, it is ignored. Another feature of this function is:

If no callback function is provided, all items in the array whose value is FALSE are deleted.

Bool bool bool bool bool bool bool bool bool

Note: If the callback function is left blank, values 0, 0.0, and the ‘0’ string 0 that might make sense are removed. Write your own callback function if the cleanup rules are different.

0x06 Verify that all array members are true

Sometimes we want to verify that all values in an array are true, such as [‘read’ => true, ‘write’ => true, ‘execute’ => true]. Do we need a loop? NO, NO, NO… All you need to do is use the array_product function. The code is as follows:

<? php $power = ['read' => true, 'write' => true, 'execute' => true]; var_dump((bool)array_product($power)); $power = ['read' => true, 'write' => true, 'execute' => false]; var_dump((bool)array_product($power)); // result false copies the codeCopy the code

Why is this possible? Array_product (array_product, array_product, array_product, array_product, array_product, array_product, array_product, array_product, array_product) When passing an array of bool members, we know that true is converted to 1 and false to 0. And then as soon as there’s a false in the array it’s going to be zero, and then we’re going to make it bool and it’s going to be false.

Note: Using the array_product function converts an array member to a numeric type during the calculation, so make sure you know the value of the array member, otherwise you will get unexpected results. Such as:

<? php $power = ['read' => true, 'write' => true, 'execute' => 'true']; var_dump((bool)array_product($power)); // result false copies the codeCopy the code

The above example is because ‘true’ is converted to 0 in the calculation. Click here for more details.

0x07 Gets the array before/after the specified key name

What if we only want the part of the associative array before the specified key value? Another cycle? No, we can use array_keys, array_search, and array_slice. The following code is posted:

<? php $data = ['first' => 1, 'second' => 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')); // result [] var_dump(beforeKey($data, 'second')); / / the result [' first '= > 1] var_dump (beforeKey ($data,' third ')); // result ['first' => 1, 'second' => 2] copies the codeCopy the code

Array_slice (array_slice, array_slice, array_slice, array_slice, array_slice, array_slice, array_slice, array_slice, array_slice, array_slice, array_slice The question to solve is “how do I get the offset of the key name?” The array_keys function returns some or all of the key names in the array. By default, it returns all of the key names. The array of key names is indexed numerically. In this example, the original array becomes: [0 => ‘first’, 1 => ‘second’, 2 => ‘third’]. We can then get the offset of the specified key name by using array_search, because this function “searches the array for the given value and returns the first corresponding key name on success”. With the offset we can do this by calling array_slice directly.

Getting the array after the specified key is easy, with a slight modification to array_slice. Post code directly:

<? php $data = ['first' => 1, 'second' => 2, 'third' => 3]; function afterKey($array, $key) { $keys = array_keys($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 ')); / / the result [' third '= > 3] var_dump (afterKey ($data,' third ')); // Result [] copies the codeCopy the code

So how do you get an array before or after the specified value? BeforeKey ($data, array_search($value, $data))

0x08 The most repeated value in the array

Type on the blackboard and underline! It is said that this is an interview question. Given an array [6, 11, 11, 2, 4, 4, 11, 6, 7, 4, 2, 11, 8], how do I get the most repeated value in the array? The key is the array_count_values function. Example code is as follows:

<? php $data = [6, 11, 11, 2, 4, 4, 11, 6, 7, 4, 2, 11, 8]; $cv = array_count_values($data); // $cv = [6 => 2, 11 => 4, 2 => 2, 4 => 3, 7 => 1, 8 => 1] arsort($cv); $max = key($cv); var_dump($max); Result 11 Copies the codeCopy the code

The array_count_values function “counts all the values in the array”. That is, the value in the original array is used as the key name of the returned array, and the number of occurrences of the value is used as the value of the returned array. This allows us to use the arsort function to sort the occurrences in descending order and maintain index association. Finally, we use key to get the key name of the current cell (the current cell defaults to the first member of the array), in which case the key name is the most repeated value of the original array.

0x09 Commercial break

PHP provides a lot of array-related functions, but it’s not very convenient to use and they are called by functions without object-oriented implementation. So I’ve been working on an open source utility class project called Zane /utils, which encapsulates some common methods and supports chained calls. The Ary class implements “get the most repeated value in an array” on a single line, as follows:

$data = [6, 11, 11, 2, 4, 4, 11, 6, 7, 4, 2, 11, 8]; $max = Ary::new($data)->countValues()->maxKey(); var_dump($max); 11 / / resultsCopy the code