Home  >  Article  >  Daily Programming  >  Detailed explanation of PHP arrays (knock on the blackboard)

Detailed explanation of PHP arrays (knock on the blackboard)

**熬夜选手
**熬夜选手Original
2020-05-01 09:58:15369browse

What is an array?

Array refers to combining several data into a whole in a certain order

Arrays have the following definitions:

//形式1:
$arr1  =  array(单元1,单元2,...);
//形式2:
$arr2  =  [单元1,单元2,...];

Index array and associative array

Index array

Usually refers to an array whose subscripts are consecutive integers starting from 0

//举例:
$arr = [1, 3,  5,  22,  12];

Associative array

Usually means that the subscripts of an array are all strings

$person = array(
‘name’=>’张三’,
‘age’=>18,  
‘edu’=> ‘大学’,  
);

Traversal of arrays

Use the foreach statement to traverse the array

foreach( $数组名  as  [$key =>] $value){
}

Use the for loop statement to traverse the array

Array pointer: There is a "pointer" inside each array. Under normal circumstances, the pointer points to a certain unit of the array, and initially points to the first unit by default.

In the initial state, the pointer points to the first element of the array.

In php, there are the following functions, which can perform corresponding operations on array pointers:

$re  =  current( $arr1);  //取得数组中当前指针所在单元的值;
$re  =  key( $arr1 );  //取得数组中当前指针所在单元的键(下标);
$re  =  next( $arr1 );  //将数组中的指针往后移动一个位置,并取得新位置上的值;
$re  =  prev( $arr1 );  //将数组中的指针往前移动一个位置,并取得新位置上的值;
$re  =  end( $arr1 );  //将数组中的指针移动到最后一个位置,并取得新位置上的值;
$re  =  reset($arr1);  //将数组中的指针移动到最前一个位置,并取得新位置上的值;

Commonly used array functions

max():  //获取一个数组中的最大值
min():  //获取一个数组中的最小值
count():  //获取一个数组的元素个数
in_array(): //判断一个数据是否在指定数组中。
range():    //生成某个范围的连续值的数组
array_keys(): //取出一个数组中的所有“键”并放入一个索引数组中。
array_push(): //将一个或多个数据放入一个数组的“末端”。
array_pop():  //将一个数组的最后一个单元删除,并返回该单元的值。
array_reverse(): //将一个数组的所有单元的顺序进行反转

Summary:

#In order to facilitate processing in the program, several variables of the same type are organized in an orderly manner. An array is formed.

Proper use of arrays in a program will make the structure of the program neater, and more complex operations can be converted into simple arrays to represent them.

The above is the detailed content of Detailed explanation of PHP arrays (knock on the blackboard). 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