A brief introduction to arrays in PHP tutorial
1. Overview
Simple introduction and basic use
Usage of common standard library functions for php arrays
php array simulates common data structures
Instructions and points for attention when using php array
-
FAQ
2. Brief introduction and basic use
The array in PHP is actually an ordered map. A map is a type that associates values to keys.
Through
<?php $arr = array(1, 2, 3, 4);
An ordinary array is definedWe can also define associative arrays
<?php $arr = array('a' => 1, 'z' => 100); >1
If the PHP version >= 5.4, we can define the array in a more concise way
<?php $arr = [1, 2, 3, 4]; $arr = ['a' => 1, 'z' => 100]; 123
php arrays are very powerful and can define mixed type arrays
<?php $arr = [1, 'hello' => '11', 'arr' => [1, 'a'=>'b']];12
About array access Operation, you can access it through
[index]
:
<?php $arr = [1, 'hello' => '11', 'arr' => [1, 'a'=>'b']]; var_dump($arr[0]); // 1var_dump($arr['arr']); // [1, 'a' => 'b']1234
You can also modify the value of the array element through
[]
<?php $arr = [1, 'hello' => '11', 'arr' => [1, 'a'=>'b']];$arr[0] = 'test'; var_dump($arr); 1234
You can also continue to add array elements in the initialized array
<?php$arr = [1, 2, 3, 4]; //追加元素$arr[] = 'a';// 添加 key, value$arr['test'] = 'b';123456
Of course, The operation of deleting array elements must support
<?php$arr = [1, 'hello' => '11', 'arr' => [1, 'a'=>'b']];unset($arr['hello']); var_dump($arr['hello']); // null1234
In development, it is often necessary to traverse the array, you can use foreach:
<?php $arr = [1, 'hello' => '11', 'arr' => [1, 'a'=>'b']];foreach($arr as $key => $value) { var_dump($key . ' => ' . $value); }12345
For more methods of array traversal, please refer to php-array traversal
- Comparison between arrays. Arrays cannot be compared in size, but they can be judged to be equal according to certain conditions
<?php // $a == $b 相等 如果 $a 和 $b 具有相同的键/值对则为 TRUE。 // $a === $b 全等 如果 $a 和 $b 具有相同的键/值对并且顺序和类型都相同则为 TRUE。$a = [1, 2];$b = ['1' => 2, 0 => 1]; var_dump($a == $b); // truevar_dump($a === $b); // false123456789
3. Practical arrays Tool function
After mastering the basic operations of arrays (definition and use, addition, deletion, modification, search, traversal), you can use arrays in development, but these operations alone are not enough. In order to meet the needs of complex and changeable To meet the needs of array operations in development scenarios, PHP provides a powerful set of Array operation functions
- Get the array length
<?php $arr = [1, 2, 3]; var_dump(count($arr)); // 3123
If you want to determine whether a variable is an array, you can Through is_array():
<?php $arr = [1, 2, 3];$notArr = '111'; var_dump(is_array($arr)); // truevar_dump(is_array($notArr)); // false12345
More key or value, determine whether the element is in the array
// 判断key 是否在数组中$arr = ['a' => 2, 4]; var_dump(isset($arr['a'])); // true var_dump(array_key_exists('a', $arr)); // true// 判断 value 是否在数组中in_array(5, $arr); // false1234567
Get all the keys of the array
<?php $arr = ['a' => 2, 4];$keys = array_keys($arr); // ['a', 1]123
Get all the values of the array
<?php $arr = ['a' => 2, 4];$values = array_values($arr); // [2, 4]123
To count the number of times each element value of an array appears, you can use array_count_values:
<?php$arr = [1, 3, 2, 'a' => 1, 'b' => 2]; var_dump(array_count_values($arr));/* array(3) { [1]=> int(2) [3]=> int(1) [2]=> int(2) } */1234567891011121314
Operations between arrays: An array can be regarded as a set, between sets Operations (intersection, difference, union, complement, comparison, etc.) PHP also provides corresponding methods to realize the merging of
<?php$arr1 = ['a' => 1, 2, 'b' => 3];$arr2 = ['b' => 5, 2]; var_dump( array_merge($arr1, $arr2) ); /* array(4) { ["a"]=> int(1) [0]=> int(2) ["b"]=> int(5) [1]=> int(2) } // 你也可以使用 + 操作符, 请注意两种方法结果的差别 var_dump($arr1 + $arr2); */12345678910111213141516171819
If you need to calculate the intersection of two or more array values, you can use
array_intersect
<?php$arr1 = [1, 2, 3];$arr2 = [5, 2]; var_dump( array_intersect($arr1, $arr2) ); // [2]1234
Difference set of arrays (by value and by key)
<?php$a = [1, 2];$b = ['1' => 2, 0 => 1, 4];//array_diff 按照索引 和 值 比较差异var_dump(array_diff($a, $b));// array_diff_key() 函数用于比较两个(或更多个)数组的键名 ,并返回差集 var_dump(array_diff_key($a, $b)); 123456789
If you need to obtain a subarray, you can use array_slice to produce an effect similar to python slicing
<?php$arr = [1, 2, 3, 4, 5, 6, 7, 8];// 从第3个元素开始, 直到结束var_dump(array_slice($arr, 2));// 从第3个元素开始, 长度为4var_dump(array_slice($arr, 2, 4));// 从第3个元素开始,到倒数第3个元素var_dump(array_slice($arr, 2, -2));// 注意 索引的差别var_dump(array_slice($arr, 2, -2, true));12345678910111213
Regarding the sorting operation of arrays, it is also a relatively common development requirement. It should be noted that: php sorting functions directly act on the array itself, rather than returning A new sorted array. , The following code provides several common scenarios. For more information, please refer to PHP to sort arrays:
<?php// 按照值(value)升序排序, 索引更新$arr = [6,'a'=>2, 3, 4, 6, -1, 7, 8]; sort($arr); var_dump($arr);// 按照值(value)升序排序, 索引保持$arr = [6,'a'=>2, 3, 4, 6, -1, 7, 8]; asort($arr); var_dump($arr);// 按照值(value)降序排序, 索引保持$arr = [6,'a'=>2, 3, 4, 6, -1, 7, 8]; arsort($arr); var_dump($arr);// 按照 键(key)进行升序排序 , 索引保持$arr = ['a' => 10, 'c' => 1, 'b' => 12]; ksort($arr); var_dump($arr);// 按照 键(key)进行降序排序 , 索引保持$arr = ['a' => 10, 'c' => 1, 'b' => 12]; krsort($arr); var_dump($arr);// 用户自定义排序, 根据值(value) , 索引更新// 请注意:对于自定义的比较函数,// 在第一个参数小于,等于或大于第二个参数时,// 该比较函数必须相应地返回一个小于,等于或大于 0 的整数。function cmp($val1, $val2){ if($val1 > $val2) { return 1; } elseif ($val1 == $val2) { return 0; } else { return -1; } }$arr = [ 'a' => 1, 'A' => 3, 'B' => 2, ]; usort($arr, cmp); var_dump($arr);// 根据key 自定义排序规则,请使用 uksort(), 用法同usort()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
About the difference between arrays and strings Operations generally include cutting strings and merging array elements into strings. You can use explode and implode to achieve
<?phpvar_dump(explode(',', "a,a,a,a,a,a")); // 以,为分割符将字符串"a,a,a,a,a,a" 切割成数组var_dump(implode('-', [1, 2, 3, 4, 5])); //以 - 为 拼接符 将 数组[1, 2, 3, 4, 5] 拼接成字符串1234
For more array-related functions in PHP, you can Refer to the official document PHP array function list
4. Arrays simulate common data structures
php arrays can simulate common data structures, the most obvious ones are mapping tables and dictionaries , here is a brief introduction to the simulation of stacks and queues by PHP arrays.
Simulation stack (FILO)
<?php$stack = [1, 2, 3, 4];//入栈array_push($stack, -1); var_dump($stack); // [1, 2, 3, 4, -1]//出栈$e = array_pop($stack); var_dump($e); // -1var_dump($stack); // [1, 2, 3, 4]1234567891011
Simulation queue (FIFO)
<?php$queue = [];//入队列array_unshift($queue, 1); array_unshift($queue, 2); array_unshift($queue, 3); array_unshift($queue, 4);//出队列$e = array_pop($queue); var_dump($e); // 1$e = array_pop($queue); var_dump($e); // 2$e = array_pop($queue); var_dump($e); // 3$e = array_pop($queue); var_dump($e); // 4123456789101112131415161718
5. Instructions and precautions for using php arrays
php array key value will have the following forced conversion
Strings containing legal integer values will be converted to integers. For example, the key name "8" will actually be stored as 8. But "08" will not be cast because it is not a legal decimal value.
Floating point numbers will also be converted to integers, which means their decimal parts will be rounded off. For example, the key name 8.7 will actually be stored as 8.
Boolean values will also be converted to integers. That is, the key name true will actually be stored as 1 and the key name false will be stored as 0.
Null 会被转换为空字符串,即键名 null 实际会被储存为 “”。
数组和对象不能被用为键名。坚持这么做会导致警告:Illegal offset type。
因此以下代码可能导致意外的结果,请注意以下代码的输出:
<?php$arr = [1, 2, '8' => 3];$arr[false] = -20; var_dump($arr); // [-20, 2, '8' => 3]$arr[8] = 20; var_dump($arr); // [-20, 2, 8 => 20]$arr[8.7] = 15; var_dump($arr); // [-20, 2, 8 => 15]$arr["8.7"] = 10; var_dump($arr); // [-20, 2, 8 => 10]$arr[$val] = 5; // 注意$val之前为声明,因此默认值为null, 数组key为null时会被转为""空串 var_dump($arr); // [-20, 2, 8 => 10, "" => 5]$arr[bar] = 6; // 标识符被转化为 'bar'var_dump($arr); // [-20, 2, 8 => 10, "" => 5, 'bar' => 6]12345678910111213141516171819202122
关于php数组的类型转换
php数组可以将其他一切类型转为数组,转化的效果请参考一下代码,重点观察对 null 和 object对象的转化:
<?php$var = true; var_dump((array)$var);/* array(1) { [0]=> bool(true) }*/$var = 1; var_dump((array)$var);/* array(1) { [0]=> int(1) }*/$var = 1.1; var_dump((array)$var);/* array(1) { [0]=> float(1.1) }*/$var = "111"; var_dump((array)$var);/* array(1) { [0]=> string(3) "111" }*/$var = null; var_dump((array)$var); // 返回空数组/* array(0) { } */class Cls { public $a = 1; protected $b = 2; private $c = 3; } var_dump((array)(new Cls)); // 可见性不同 key值格式有所不同/* array(3) { ["a"]=> int(1) ["*b"]=> int(2) ["Clsc"]=> int(3) } */123456789101112131415161718192021222324252627282930313233343536373839404142434445
关于PHP类型转换的了解,请参考PHP-类型转换的判别
六、FAQ
如何添加数组元素更为高效?
array_push($arr, key, value)
or$arr[key] = value
? 答: 后者更为高效, 更多细节请参考官方资料isset or array_key_exists() ? 答:
对于存在key的数组,如果 对应的value = null ,
isset($arr[key])
会返回 false;而对于array_key_exists
只要对应key存在就会返回true;然而在效率方面,
isset
效率 高于array_key_eixsts
在判断数组元素是否存在的最佳实践如下:
<?php if (isset($arr[$key]) or array_key_exists($key, $arr)) { ...}1234
数组合并
+
和array_merge
的区别? 答:可以参考该资料array_diff
与==
的异同? 答:语义有所差别, 数组的相等比较 推荐只使用==
遍历方式那种更高效? 答:foreach 方式 遍历 最为高效
The above is the detailed content of A brief introduction to arrays in PHP tutorial. 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

AI Hentai Generator
Generate AI Hentai for free.

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

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

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

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.
