Home>Article>Backend Development> How to use PHP arrays

How to use PHP arrays

不言
不言 Original
2018-07-09 10:08:00 2362browse

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 // )

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 // )

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:


      

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;

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, ', '; }
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;

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 // )

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]

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]

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 // )

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]

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!

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:


      

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 // )

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

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 // )
译注:有关合并数组操作还有一个「+」号运算符,它和 array_merge()函数的功能类似都可以完成合并数组运算,但是结果有所不同,可以查看 PHP 合并数组运算符 + 与 array_merge 函数 了解更多细节。

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

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

数组的数学运算

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


      

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

41cd024259fee57a3f70060824ab3c97 2 // [banana] => 1 // [tree] => 3 // )

生成数组

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

8820f44454f0fd2ffffa31f308b79687 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

总结

正如你所看到的那样,掌握主要的数组函数可以是我们的代码更精简且易于阅读。当然,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!

Statement:
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