How to use PHP arrays

不言
Release: 2023-04-02 21:42:02
Original
2433 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:

<?php
$keys = [&#39;sky&#39;, &#39;grass&#39;, &#39;orange&#39;];
$values = [&#39;blue&#39;, &#39;green&#39;, &#39;orange&#39;];

$array = array_combine($keys, $values);

print_r($array);
// Array
// (
//     [sky] => 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:

<?php

print_r(array_keys($array));// [&#39;sky&#39;, &#39;grass&#39;, &#39;orange&#39;]

print_r(array_values($array));// [&#39;blue&#39;, &#39;green&#39;, &#39;orange&#39;]

print_r(array_flip($array));
// Array
// (
//     [blue] => 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 the list() function is given below:

<?php
// 定义数组
$array = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];

// 不使用 list()
$a = $array[0];
$b = $array[1];
$c = $array[2];

// 使用 list() 函数
list($a, $b, $c) = $array;
Copy after login

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 = &#39;hello|wild|world&#39;;

list($hello, , $world) = explode(&#39;|&#39;, $string);
echo $hello, &#39; &#39;, $world;
Copy after login

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, &#39;, &#39;;
}
Copy after login
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 = [
    &#39;clothes&#39; => &#39;t-shirt&#39;,
    &#39;size&#39; => &#39;medium&#39;,
    &#39;color&#39; => &#39;blue&#39;,
];

extract($array);

echo $clothes, &#39; &#39;, $size, &#39; &#39;, $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 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 = &#39;t-shirt&#39;;
$size = &#39;medium&#39;;
$color = &#39;blue&#39;;

$array = compact(&#39;clothes&#39;, &#39;size&#39;, &#39;color&#39;);
print_r($array);

// Array
// (
//     [clothes] => 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 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]
Copy after login

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

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

<?php
$array = [
    [&#39;id&#39; => 1, &#39;title&#39; => &#39;tree&#39;],
    [&#39;id&#39; => 2, &#39;title&#39; => &#39;sun&#39;],
    [&#39;id&#39; => 3, &#39;title&#39; => &#39;cloud&#39;],
];

$ids = array_column($array, &#39;id&#39;);

print_r($ids);// [1, 2, 3]
Copy after login

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, &#39;id&#39;); // 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:

<?php
$cities = [&#39;Berlin&#39;, &#39;KYIV&#39;, &#39;Amsterdam&#39;, &#39;Riga&#39;];
$aliases = array_map(&#39;strtolower&#39;, $cities);

print_r($aliases);// [&#39;berlin&#39;, &#39;kyiv, &#39;amsterdam&#39;, &#39;riga&#39;]

$numbers = [1, -2, 3, -4, 5];
$squares = array_map(function ($number) {
    return $number ** 2;
}, $numbers);

print_r($squares);// [1, 4, 9, 16, 25]
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:

<?php
$model = [&#39;id&#39; => 7, &#39;name&#39; => &#39;James&#39;];
$res = array_map(function ($key, $value) {
    return $key . &#39; is &#39; . $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 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 = [
    &#39;banana&#39; => &#39;yellow&#39;,
    &#39;apple&#39; => &#39;green&#39;,
    &#39;orange&#39; => &#39;orange&#39;,
];

array_walk($fruits, function (&$value, $key) {
    $value = $key . &#39; is &#39; . $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:

<?php
$array1 = [&#39;a&#39; => &#39;a&#39;, &#39;b&#39; => &#39;b&#39;, &#39;c&#39; => &#39;c&#39;];
$array2 = [&#39;a&#39; => &#39;A&#39;, &#39;b&#39; => &#39;B&#39;, &#39;D&#39; => &#39;D&#39;];
 
$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() 函数获取所有数组都存在的值(译注:获取交集)。接下来的示例演示它们的使用方法:

<?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]
Copy after login

数组的数学运算

使用 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
Copy after login

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

<?php

$things = [&#39;apple&#39;, &#39;apple&#39;, &#39;banana&#39;, &#39;tree&#39;, &#39;tree&#39;, &#39;tree&#39;];
$values = array_count_values($things);

print_r($values);

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

生成数组

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

<?php
$bind = array_fill(0, 5, &#39;?&#39;);
print_r($bind);
Copy after login

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

<?php
$letters = range(&#39;a&#39;, &#39;z&#39;);
print_r($letters); // [&#39;a&#39;, &#39;b&#39;, ..., &#39;z&#39;]

$hours = range(0, 23);
print_r($hours); // [0, 1, 2, ..., 23]
Copy after login

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

<?php
$numbers = range(1, 10);
$top = array_slice($numbers, 0, 3);

print_r($top);// [1, 2, 3]
Copy after login

排序数组

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

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

  • k 依据键名排序

  • r 对数组进行逆向排序

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

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


akru
aasort
arsortuasort
k
ksortkrsort
rarsortkrsortrsort
uuasort

usort

数组函数的组合使用

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

<?php
$values = [&#39;say&#39;, &#39;  bye&#39;, &#39;&#39;, &#39; to&#39;, &#39; spaces  &#39;, &#39;    &#39;];
$words = array_filter(array_map(&#39;trim&#39;, $values));

print_r($words);// [&#39;say&#39;, &#39;bye&#39;, &#39;to&#39;, &#39;spaces&#39;]
Copy after login

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

<?php
$models = [$model, $model, $model];

$id_to_title = array_combine(
    array_column($models, &#39;id&#39;),
    array_column($models, &#39;title&#39;)
);

print_r($id_to_title);
Copy after login
译注:提供一个 可运行的版本。

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

<?php

$letters = [&#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;b&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;d&#39;, &#39;d&#39;, &#39;d&#39;, &#39;d&#39;];

$values = array_count_values($letters);
arsort($values);
$top = array_slice($values, 0, 3);

print_r($top);
Copy after login

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

<?php
$order = [
    [&#39;product_id&#39; => 1, &#39;price&#39; => 99, &#39;count&#39; => 1],
    [&#39;product_id&#39; => 2, &#39;price&#39; => 50, &#39;count&#39; => 2],
    [&#39;product_id&#39; => 2, &#39;price&#39; => 17, &#39;count&#39; => 3],
];

$sum = array_sum(array_map(function ($product_row) {
    return $product_row[&#39;price&#39;] * $product_row[&#39;count&#39;];
}, $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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template