Home >Backend Development >PHP Tutorial >A brief introduction to arrays in PHP tutorial

A brief introduction to arrays in PHP tutorial

巴扎黑
巴扎黑Original
2017-08-09 14:41:221298browse

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