How to use PHP arrays

不言
Release: 2023-04-02 21:42:02
Original
2367 people have browsed it

This article mainly introduces the use of PHP arrays, which has certain reference value. Now I share it with everyone. Friends in need can refer to it.

In this tutorial, I will use some practical examples and Lists the commonly used array functions in PHP in a best-practice way. Every PHP engineer should know how to use them and how to combine them to write leaner and more readable code.

In addition, we provide a presentation of relevant sample code, which you can download from the relevant link and share with your team to build a stronger team.

Getting Started

Let us start with some basic array functions that deal with array keys and values. array_combine(), as a member of the array function, is used to create a new array by using the value of one array as its key name and the value of another array as its value:

 blue // [grass] => green // [orange] => orange // )
Copy after login

You should know that array_values () function will return the values in the array in the form of an indexed array, array_keys() will return the key name of the given array, and array_flip() function, its function is to exchange the key value and key name in the array:

 sky // [green] => grass // [orange] => orange // )
Copy after login

Simplify the code

list() function, to be precise, it is not a function, but a language structure that can assign values in an array to a set of variables in a single operation. For example, the basic usage of thelist()function is given below:


        
Copy after login

This language structure is combined withpreg_split()orexplode()This type of function is more effective. If you don’t need to define some of the values, you can directly skip the assignment of some parameters:

$string = 'hello|wild|world'; list($hello, , $world) = explode('|', $string); echo $hello, ' ', $world;
Copy after login

In addition,list()can also be usedforeachTraversal, this usage can better take advantage of this language structure:

$arrays = [[1, 2], [3, 4], [5, 6]]; foreach ($arrays as list($a, $b)) { $c = $a + $b; echo $c, ', '; }
Copy after login
Translator’s Note: The list() language structure is only applicable to numerical index arrays, and the default index starts from 0starts and cannot be used with associative arrays, see the documentation.

And by using the extract() function, you can export the associative array into a variable (symbol table). For each element in the array, its key name will be used as the variable name to create, and the value of the variable will be the value of the corresponding element:

 't-shirt', 'size' => 'medium', 'color' => 'blue', ]; extract($array); echo $clothes, ' ', $size, ' ', $color;
Copy after login

Note when processing user data (such as requested data)The extract()function is a safe function, so at this time it is better to use better flag types such asEXTR_IF_EXISTSandEXTR_PREFIX_ALL.

extract()The inverse operation of the function is the compact() function, which is used to create associative arrays by variable names:

 t-shirt // [size] => medium // [color] => blue // )
Copy after login

Filter function

PHP Provides an awesome function for filtering arrays, array_filter(). Use the array to be processed as the first parameter of the function, and the second parameter is an anonymous function. If you want the elements in the array to pass validation, the anonymous function returnstrue, otherwise returnsfalse: The

 0; }); print_r($positive);// [0 => 20, 2 => 50, 4 => 55]
Copy after login

function not only supports filtering by value. You can also useARRAY_FILTER_USE_KEYorARRAY_FILTER_USE_BOTHas the third parameter to specify whether to use the key value of the array or both the key value and the key name as parameters of the callback function.

You can also define a callback function in thearray_filter()function to remove null values:

 -1, 2 => 1]
Copy after login

You can use the array_unique() function to get unique values from the array value element. Note that this function will retain the key name of the unique element in the original array:

 1 // [4] => 2 // [7] => 3 // [8] => 4 // [9] => 5 // )
Copy after login

array_column() function can obtain the value of the specified column from a multi-dimensional array (multi-dimensional), such as obtaining answers from a SQL database or CSV File import data. Just pass in the array and the specified column name:

 1, 'title' => 'tree'], ['id' => 2, 'title' => 'sun'], ['id' => 3, 'title' => 'cloud'], ]; $ids = array_column($array, 'id'); print_r($ids);// [1, 2, 3]
Copy after login

Starting from PHP 7,array_columnis more powerful because it starts to support arrays containing objects, so it changes when dealing with array models. Easier:

all(); $cinema_ids = array_column($cinemas, 'id'); // php7 forever!
Copy after login

Array traversal processing

By using array_map(), you can execute a callback method on each element in the array. You can get a new array based on the given array by passing in a function name or an anonymous function:


        
Copy after login

There is also a rumor about this function that you cannot pass the key name and key value of the array to the callback function at the same time. But we're going to break it down now:

 7, 'name' => 'James']; $res = array_map(function ($key, $value) { return $key . ' is ' . $value; }, array_keys($model), $model); print_r($res); // Array // ( // [0] => id is 7 // [1] => name is James // )
Copy after login

But it's really ugly to do it this way. It's better to use the array_walk() function instead. This function behaves similarly toarray_map(), but its working principle is completely different. First, the array is passed in by reference, soarray_walk()will not create a new array, but directly modify the original array. So as the source array, you can pass the value of the array into the callback function using the reference passing method, and just pass the key name of the array directly:

 'yellow', 'apple' => 'green', 'orange' => 'orange', ]; array_walk($fruits, function (&$value, $key) { $value = $key . ' is ' . $value; }); print_r($fruits);
Copy after login

Array connection operation

In PHP The best way to merge arrays is to use the array_merge() function. All array options will be merged into one array, and values with the same key name will be overwritten by the last value:

 'a', 'b' => 'b', 'c' => 'c']; $array2 = ['a' => 'A', 'b' => 'B', 'D' => 'D']; $merge = array_merge($array1, $array2); print_r($merge); // Array // ( // [a] => A // [b] => B // [c] => c // [D] => D // )
Copy after login
译注:有关合并数组操作还有一个「+」号运算符,它和 array_merge()函数的功能类似都可以完成合并数组运算,但是结果有所不同,可以查看 PHP 合并数组运算符 + 与 array_merge 函数 了解更多细节。

为了实现从数组中删除不在其他数组中的值(译注:计算差值),使用 array_diff()。还可以通过 array_intersect() 函数获取所有数组都存在的值(译注:获取交集)。接下来的示例演示它们的使用方法:

 1, 1 => 2] print_r($intersect); //交集 [2 => 3, 3 => 4]
Copy after login

数组的数学运算

使用 array_sum() 对数组元素进行求和运算,array_product 对数组元素执行乘积运算,或者使用 array_reduce() 处理自定义运算规则:


        
Copy after login

为了实现统计数组中值的出现次数,可以使用 array_count_values() 函数。它将返回一个新数组,新数组键名为待统计数组的值,新数组的值为待统计数组值的出现次数:

 2 // [banana] => 1 // [tree] => 3 // )
Copy after login

生成数组

需要以给定值生成固定长度的数组,可以使用 array_fill() 函数:


        
Copy after login

根据范围创建数组,如小时或字母,可以使用 range() 函数:


        
Copy after login

为了实现获取数组中的部分元素 - 比如,获取前三个元素 - 使用 array_slice() 函数:


        
Copy after login

排序数组

首先谨记 PHP 中有关排序的函数都是引用传值的,排序成功返回true排序失败返回false。排序的基础函数是 sort() 函数,它执行排序后的结果不会保留原索引顺序。排序函数可以归类为以下几类:

  • a保持索引关系进行排序

  • k依据键名排序

  • r对数组进行逆向排序

  • u使用用户自定义排序规则排序

你可以从下表看到这些排序函数:


a k r u
a asort
arsort uasort
k
ksort krsort
r arsort krsort rsort
u uasort

usort

数组函数的组合使用

数组处理的艺术是组合使用这些数组函数。这里我们通过array_filter()array_map()函数仅需一行代码就可以完成空字符截取和去控制处理:


        
Copy after login

依据模型数组创建 id 和 title 数据字典,我们可以结合使用array_combine()array_column()函数:


        
Copy after login
译注:提供一个 可运行的版本。

为了实现获取出现频率最高的数组元素,我们可以使用array_count_values()arsort()array_slice()这几个函数:


        
Copy after login

还可以轻易的通过array_sum()array_map()函数仅需数行就能完成计算订单的价格:

 1, 'price' => 99, 'count' => 1], ['product_id' => 2, 'price' => 50, 'count' => 2], ['product_id' => 2, 'price' => 17, 'count' => 3], ]; $sum = array_sum(array_map(function ($product_row) { return $product_row['price'] * $product_row['count']; }, $order)); print_r($sum);// 250
Copy after login

总结

正如你所看到的那样,掌握主要的数组函数可以是我们的代码更精简且易于阅读。当然,PHP 提供了比列出来的要多得多的数组函数,并且还提供了额外参数及标识参数,但是我觉得本教程中已经涵盖了 PHP 开发者应该掌握的最基本的一些。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

PHP缓存区ob的介绍

为多个PHP-FPM容器量身打造单一Nginx镜像的方法

The above is the detailed content of How to use PHP arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!