search
HomeBackend DevelopmentPHP TutorialA brief introduction to arrays in PHP tutorial
A brief introduction to arrays in PHP tutorialAug 09, 2017 pm 02:41 PM
phpintroduceSimple

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 defined

  • We can also define associative arrays

<?php  $arr = array(&#39;a&#39; => 1, &#39;z&#39; => 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 = [&#39;a&#39; => 1, &#39;z&#39; => 100]; 123
  • php arrays are very powerful and can define mixed type arrays

<?php $arr = [1, &#39;hello&#39; => &#39;11&#39;, &#39;arr&#39; => [1, &#39;a&#39;=>&#39;b&#39;]];12
  • About array access Operation, you can access it through [index]:

<?php $arr = [1, &#39;hello&#39; => &#39;11&#39;, &#39;arr&#39; => [1, &#39;a&#39;=>&#39;b&#39;]];
var_dump($arr[0]); // 1var_dump($arr[&#39;arr&#39;]); // [1, &#39;a&#39; => &#39;b&#39;]1234
  • You can also modify the value of the array element through []

<?php $arr = [1, &#39;hello&#39; => &#39;11&#39;, &#39;arr&#39; => [1, &#39;a&#39;=>&#39;b&#39;]];$arr[0] = &#39;test&#39;;
var_dump($arr);  1234
  • You can also continue to add array elements in the initialized array

<?php$arr = [1, 2, 3, 4]; 
//追加元素$arr[] = &#39;a&#39;;// 添加 key, value$arr[&#39;test&#39;] = &#39;b&#39;;123456
  • Of course, The operation of deleting array elements must support

<?php$arr = [1, &#39;hello&#39; => &#39;11&#39;, &#39;arr&#39; => [1, &#39;a&#39;=>&#39;b&#39;]];unset($arr[&#39;hello&#39;]);
var_dump($arr[&#39;hello&#39;]);  // null1234
  • In development, it is often necessary to traverse the array, you can use foreach:

<?php $arr = [1, &#39;hello&#39; => &#39;11&#39;, &#39;arr&#39; => [1, &#39;a&#39;=>&#39;b&#39;]];foreach($arr as $key => $value) {
    var_dump($key . &#39; => &#39; . $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 = [&#39;1&#39; => 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 = &#39;111&#39;;
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 = [&#39;a&#39; => 2, 4];
var_dump(isset($arr[&#39;a&#39;])); // true  var_dump(array_key_exists(&#39;a&#39;, $arr)); // true// 判断 value 是否在数组中in_array(5, $arr);  // false1234567
  • Get all the keys of the array

<?php $arr = [&#39;a&#39; => 2, 4];$keys = array_keys($arr); // [&#39;a&#39;, 1]123
  • Get all the values ​​of the array

<?php $arr = [&#39;a&#39; => 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, &#39;a&#39; => 1, &#39;b&#39; => 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 = [&#39;a&#39; => 1, 2, &#39;b&#39; => 3];$arr2 = [&#39;b&#39; => 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 = [&#39;1&#39; => 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,&#39;a&#39;=>2, 3, 4, 6, -1, 7, 8];
sort($arr);
var_dump($arr);// 按照值(value)升序排序, 索引保持$arr = [6,&#39;a&#39;=>2, 3, 4, 6, -1, 7, 8];
asort($arr);
var_dump($arr);// 按照值(value)降序排序, 索引保持$arr = [6,&#39;a&#39;=>2, 3, 4, 6, -1, 7, 8];
arsort($arr);
var_dump($arr);// 按照 键(key)进行升序排序 , 索引保持$arr = [&#39;a&#39; => 10, &#39;c&#39; => 1, &#39;b&#39; => 12];
ksort($arr);
var_dump($arr);// 按照 键(key)进行降序排序 , 索引保持$arr = [&#39;a&#39; => 10, &#39;c&#39; => 1, &#39;b&#39; => 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 = [    &#39;a&#39; => 1,    &#39;A&#39; => 3,    &#39;B&#39; => 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(&#39;,&#39;, "a,a,a,a,a,a")); // 以,为分割符将字符串"a,a,a,a,a,a" 切割成数组var_dump(implode(&#39;-&#39;, [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, &#39;8&#39; => 3];$arr[false] = -20;
var_dump($arr); // [-20, 2, &#39;8&#39; => 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; // 标识符被转化为 &#39;bar&#39;var_dump($arr); // [-20, 2, 8 => 10, "" => 5, &#39;bar&#39; => 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!

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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!