Home >Backend Development >PHP Tutorial >What are the operations of php array functions? Application of php array function (with code)
What this article brings to you is what are the operations of PHP array functions? The application of PHP array functions (with code) has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
PHP’s array is a very powerful data type. At the same time, PHP has a series of built-in array-related functions that can easily implement daily development functions. But I find that many friends seem to have ignored the role of built-in functions (for example, I have written some codes related to array operations and then found that PHP comes with /(ㄒoㄒ)/~~). Make good use of PHP's built-in functions. It greatly improves development efficiency and operating efficiency (built-in functions are written in C and are much more efficient than those written in PHP), so this article summarizes some implementation methods of using PHP built-in functions in common scenarios. In addition, if you want to learn more about PHP array functions, it is best to check the PHP manual! Click here to see the official array function manual
Get the specified key name
For some associative arrays, sometimes we only want to get the part of the specified key name, such as an array is['id' => 1, 'name' => 'zane', 'password' => '123456']
What if you only want to get the part containing id and name? What about implementation? Paste the code directly below.
<?php $raw = ['id' => 1, 'name' => 'zane', 'password' => '123456']; // 自己用 PHP 实现 function onlyKeys($raw, $keys) { $new = []; foreach ($raw as $key => $val) { if (in_array($key, $keys)) { $new[$key] = $val; } } return $new; } // 用 PHP 内置函数实现 function newOnlyKeys($array, $keys) { return array_intersect_key($array, array_flip($keys)); } var_dump(onlyKeys($raw, ['id', 'name'])); // 结果 ['id' => 1, 'name' => 'zane'] var_dump(newOnlyKeys($raw, ['id', 'name'])); // 结果 ['id' => 1, 'name' => 'zane']
Obviously there is a lot of simplicity! But what the hell are array_intersect_key
and array_flip
? Here is a brief introduction to the functions of these two functions. The first is the array_flip
function. The function of this function is to "swap the keys and values of the array", that is, the key name becomes the value, and the value becomes the key. name. The $keys
parameter we passed passed through this function and changed from [0 => 'id', 1 => 'name']
to ['id' = > 0, 'name' => 1]
. The purpose of this is to serve the array_intersect_key
function. The function of the array_intersect_key
function is to "use key name comparison to calculate the intersection of arrays", that is, to return the difference between the first parameter array and other Values with the same key name in the parameter array. In this way, the function of getting the specified key name ~(≧▽≦)/~ is realized! Of course, to understand the functions of these two functions in detail, you still need to check the PHP official manual: array_flip array_intersect_key
Remove the specified key name
With the previous example as a foreshadowing, Let’s just talk about this briefly, the principles are similar with minor differences.
<?php $raw = ['id' => 1, 'name' => 'zane', 'password' => '123456']; // 用 PHP 内置函数实现 function removeKeys($array, $keys) { return array_diff_key($array, array_flip($keys)); } // 移除 id 键 var_dump(removeKeys($raw, ['id', 'password'])); // 结果 ['name' => 'zane']
Compared with the previous example, this example just changes the array_intersect_key
function to array_diff_key
, well... I believe you can guess the function of this function "Use key Compare and calculate the difference set of arrays", which is just the opposite of the function of array_intersect_key
. Official manual: array_diff_key
Array deduplication
I believe everyone has this need. Of course, PHP also has a built-in array_unique function for everyone to use, as shown 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); // 结果 ['you are' => 666, 'i am' => 233]
Hey, using this function can solve most of the problems, but sometimes you may feel that it is not fast enough for the following reasons:
array_unique() First put the value as The strings are sorted, then for each value only the first encountered key is retained, and all subsequent keys are ignored.
Because this function will sort the array first, the speed may not meet the expected requirements in some scenarios.
Now we can use our black technology array_flip
function. As we all know, the key names of arrays in PHP are unique, so duplicate values will be ignored after the key names and values are swapped. Just imagine if we call the array_flip
function twice in a row, is it equivalent to realizing the function of the array_unique
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); // 结果 ['she is' => 666, 'he is' => 233]
Huh? ! The result is different from array_unique
! Why, we can get the answer from the PHP official manual:
If the same value appears multiple times, the last key name will be used as its value, and the other keys will be discarded.
In general, array_unique
retains the first appearing key name, array_flip
retains the last appearing key name.
Note: When using array_flip
as an array to deduplicate, the value of the array must be able to be used as a key name (that is, string type or integer type), otherwise the value will be neglect.
In addition, if we do not need to retain the key name, we can directly use array_values(array_flip($input))
.
0x04 Reset index
When we want to reset an array whose index is not continuous, such as array: [0 => 233, 99 => 666]
, for this kind of array we only need to call the array_values function to achieve it. As an example:
<?php $input = [0 => 233, 99 => 666]; var_dump(array_values($input)); // 结果 [0 => 233, 1 => 66]
It should be noted that the array_values
function not only resets the numeric index, but also deletes and resets the string key name. So how do you reset the numeric index while retaining the string key name? The answer is the array_slice function. The code example is as follows:
<?php $input = ['hello' => 'world', 0 => 233, 99 => 666]; var_dump(array_slice($input, 0)); // 结果 ['hello' => 'world', 0 => 233, 1 => 66]
array_slice
函数的功能是取出数组的中的一段,但它默认会重新排序并重置数组的数字索引,所以可以利用它重置数组中的数字索引。
清除空值
嘿,有时候我们想清除某个数组中的空值比如:null
、false
、0
、0.0
、[]空数组
、''空字符串
、'0'字符串0
,这时 array_filter 函数便能帮上大忙。代码如下:
<?php $input = ['foo', false, -1, null, '', []]; var_dump(array_filter($input)); // 结果 [0 => 'foo', 2 => -1]
为什么会出现这样的结果捏?array_filter
的作用其实是「用回调函数过滤数组中的单元」,它的第二个参数其实是个回调函数,向数组的每个成员都执行这个回调函数,若回调函数的返回值为 true
便保留这个成员,为 false
则忽略。这个函数还有一个特性就是:
如果没有提供 callback 函数, 将删除 array 中所有等值为 FALSE 的条目。
等值为 false 就是转换为 bool 类型后值为 false 的意思,详细看文档:转换为布尔类型。
注意:如果不填写 callback
函数,0
、0.0
、'0'字符串0
这些可能有意义的值会被删除。所以如果清除的规则有所不同还需要自行编写 callback
函数。
确认数组成员全部为真
有时候我们希望确认数组中的的值全部为 true
,比如:['read' => true, 'write' => true, 'execute' => true]
,这时我们需要用一个循环判定吗?NO,NO,NO……只需要用 array_product 函数便可以实现了。代码如下:
<?php $power = ['read' => true, 'write' => true, 'execute' => true]; var_dump((bool)array_product($power)); // 结果 true $power = ['read' => true, 'write' => true, 'execute' => false]; var_dump((bool)array_product($power)); // 结果 false
为什么能实现这个功能呢? array_product
函数本来的功能是「计算数组中所有值的乘积」,在累乘数组中所有成员的时候会将成员的值转为数值类型。当传递的参数为一个 bool 成员所组成的数组时,众所周知 true
会被转为 1,false
会被转为 0。然后只要数组中出现一个 false
累乘的结果自然会变成 0,然后我们再将结果转为 bool
类型不就是 false
了嘛!
注意:使用 array_product
函数将在计算过程中将数组成员转为数值类型进行计算,所以请确保你了解数组成员转为数值类型后的值,否则会产生意料之外的结果。比如:
<?php $power = ['read' => true, 'write' => true, 'execute' => 'true']; var_dump((bool)array_product($power)); // 结果 false
上例是因为 'true'
在计算过程中被转为 0。要想详细了解请点击这里。
获取指定键名之前 / 之后的数组
如果我们只想要关联数组中指定键名值之前的部分该怎么办呢?又用一个循环?当然不用我们可以通过 array_keys、array_search 和 array_slice 组合使用便能够实现!下面贴代码:
<?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')); // 结果 [] var_dump(beforeKey($data, 'second')); // 结果 ['first' => 1] var_dump(beforeKey($data, 'third')); // 结果 ['first' => 1, 'second' => 2]
思路解析,要实现这样的功能大部分同学都应该能想到 array_slice
函数,但这个函数取出部分数组是根据偏移量(可以理解为键名在数组中的顺序,从 0 开始)而不是根据键名的,而关联数组的键名却是是字符串或者是不按顺序的数字,此时要解决的问题便是「如何取到键名对应的偏移量?」,这是 array_keys
函数便帮了我们大忙,它的功能是「返回数组中部分的或所有的键名」默认返回全部键名,此外返回的键名数组是以数字索引的,也就是说返回的键名数组的索引就是偏移量!例子中的原数组变为: [0 => 'first', 1 => 'second', 2 => 'third']
。然后我们通过 array_search
便可以获得指定键名的偏移量了,因为这个函数的功能是「在数组中搜索给定的值,如果成功则返回首个相应的键名」。有了偏移量我们直接调用 array_slice
函数便可以实现目的了。
上面的例子懂了,那获取指定键名之后的数组也就轻而易举了,略微修改 array_slice
即可。直接贴代码:
<?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')); // 结果 ['second' => 2, 'third' => 3] var_dump(afterKey($data, 'second')); // 结果 ['third' => 3] var_dump(afterKey($data, 'third')); // 结果 []
那如何获取指定值之前或之后的数组呢?嘿,记得 array_search
的作用吧,其实我们只需要这样调用 beforeKey($data, array_search($value, $data))
不就实现了嘛!
数组中重复次数最多的值
敲黑板,划重点!据说这是一道面试题喔。假设有这样一个数组 [6, 11, 11, 2, 4, 4, 11, 6, 7, 4, 2, 11, 8]
,请问如何获取数组中重复次数最多的值?关键就在于 array_count_values 函数。实例代码如下:
<?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); // 结果 11
array_count_values
函数的功能是「统计数组中所有的值」,就是将原数组中的值作为返回数组的键名,值出现的次数作为返回数组的值。这样我们便可以通过 arsort 函数对出现的次数进行降序排序并且保持索引关联。最后使用 key 获得当前单元(当前单元默认为数组第一个成员)的键名,此时的键名即是原数组的值重复次数最多的值。
总结
虽然 PHP 提供了很多和数组相关的函数,但使用起来还是不算太方便而且都是通过函数的调用方式而没有面向对象相关的实现,所以我最近在写一个开源的工具类项目 zane/utils,封装了一些常用的方法并且支持链式调用,其中的 Ary 类实现 「获取数组中重复次数最多的值」只需一行,如下所示:
$data = [6, 11, 11, 2, 4, 4, 11, 6, 7, 4, 2, 11, 8]; $max = Ary::new($data)->countValues()->maxKey(); var_dump($max); // 结果 1
相关文章推荐:
The above is the detailed content of What are the operations of php array functions? Application of php array function (with code). For more information, please follow other related articles on the PHP Chinese website!