How to use PHP arrays
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:
<?php $keys = ['sky', 'grass', 'orange']; $values = ['blue', 'green', 'orange']; $array = array_combine($keys, $values); print_r($array); // Array // ( // [sky] => 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:
<?php print_r(array_keys($array));// ['sky', 'grass', 'orange'] print_r(array_values($array));// ['blue', 'green', 'orange'] print_r(array_flip($array)); // Array // ( // [blue] => 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 the list() function is given below:
<?php // 定义数组 $array = ['a', 'b', 'c']; // 不使用 list() $a = $array[0]; $b = $array[1]; $c = $array[2]; // 使用 list() 函数 list($a, $b, $c) = $array;
This language structure is combined with preg_split() or explode() 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 usedforeach Traversal, 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 0 starts 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:
<?php $array = [ 'clothes' => '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 as EXTR_IF_EXISTS and EXTR_PREFIX_ALL.
extract() The inverse operation of the function is the compact() function, which is used to create associative arrays by variable names:
<?php $clothes = 't-shirt'; $size = 'medium'; $color = 'blue'; $array = compact('clothes', 'size', 'color'); print_r($array); // Array // ( // [clothes] => 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 returns true, otherwise returns false: The
<?php $numbers = [20, -3, 50, -99, 55]; $positive = array_filter($numbers, function ($number) { return $number > 0; }); print_r($positive);// [0 => 20, 2 => 50, 4 => 55]
function not only supports filtering by value. You can also use ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH as 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 the array_filter() function to remove null values:
<?php $numbers = [-1, 0, 1]; $not_empty = array_filter($numbers); print_r($not_empty);// [0 => -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:
<?php $array = [1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 5]; $uniques = array_unique($array); print_r($uniques); print_r($array); // Array // ( // [0] => 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:
<?php $array = [ ['id' => 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_column is more powerful because it starts to support arrays containing objects, so it changes when dealing with array models. Easier:
<?php $cinemas = Cinema::find()->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:
<?php $cities = ['Berlin', 'KYIV', 'Amsterdam', 'Riga']; $aliases = array_map('strtolower', $cities); print_r($aliases);// ['berlin', 'kyiv, 'amsterdam', 'riga'] $numbers = [1, -2, 3, -4, 5]; $squares = array_map(function ($number) { return $number ** 2; }, $numbers); print_r($squares);// [1, 4, 9, 16, 25]
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:
<?php $model = ['id' => 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 to array_map(), but its working principle is completely different. First, the array is passed in by reference, so array_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:
<?php $fruits = [ 'banana' => '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:
<?php $array1 = ['a' => '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() 函数获取所有数组都存在的值(译注:获取交集)。接下来的示例演示它们的使用方法:
<?php $array1 = [1, 2, 3, 4]; $array2 = [3, 4, 5, 6]; $diff = array_diff($array1, $array2); $intersect = array_intersect($array1, $array2); print_r($diff); // 差集 [0 => 1, 1 => 2] print_r($intersect); //交集 [2 => 3, 3 => 4]
数组的数学运算
使用 array_sum() 对数组元素进行求和运算,array_product 对数组元素执行乘积运算,或者使用 array_reduce() 处理自定义运算规则:
<?php $numbers = [1, 2, 3, 4, 5]; print_r(array_sum($numbers));// 15 print_r(array_product($numbers));// 120 print_r(array_reduce($numbers, function ($carry, $item) { return $$carry ? $carry / $item : 1; }));// 0.0083 = 1/2/3/4/5
为了实现统计数组中值的出现次数,可以使用 array_count_values() 函数。它将返回一个新数组,新数组键名为待统计数组的值,新数组的值为待统计数组值的出现次数:
<?php $things = ['apple', 'apple', 'banana', 'tree', 'tree', 'tree']; $values = array_count_values($things); print_r($values); // Array // ( // [apple] => 2 // [banana] => 1 // [tree] => 3 // )
生成数组
需要以给定值生成固定长度的数组,可以使用 array_fill() 函数:
<?php $bind = array_fill(0, 5, '?'); print_r($bind);
根据范围创建数组,如小时或字母,可以使用 range() 函数:
<?php $letters = range('a', 'z'); print_r($letters); // ['a', 'b', ..., 'z'] $hours = range(0, 23); print_r($hours); // [0, 1, 2, ..., 23]
为了实现获取数组中的部分元素 - 比如,获取前三个元素 - 使用 array_slice() 函数:
<?php $numbers = range(1, 10); $top = array_slice($numbers, 0, 3); print_r($top);// [1, 2, 3]
排序数组
首先谨记 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() 函数仅需一行代码就可以完成空字符截取和去控制处理:
<?php $values = ['say', ' bye', '', ' to', ' spaces ', ' ']; $words = array_filter(array_map('trim', $values)); print_r($words);// ['say', 'bye', 'to', 'spaces']
依据模型数组创建 id 和 title 数据字典,我们可以结合使用 array_combine() 和 array_column() 函数:
<?php $models = [$model, $model, $model]; $id_to_title = array_combine( array_column($models, 'id'), array_column($models, 'title') ); print_r($id_to_title);
译注:提供一个 可运行的版本。
为了实现获取出现频率最高的数组元素,我们可以使用 array_count_values()、arsort() 和 array_slice() 这几个函数:
<?php $letters = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'd', 'd', 'd']; $values = array_count_values($letters); arsort($values); $top = array_slice($values, 0, 3); print_r($top);
还可以轻易的通过 array_sum() 和 array_map() 函数仅需数行就能完成计算订单的价格:
<?php $order = [ ['product_id' => 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中文网!
相关推荐:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
