Do you really understand PHP arrays?

Preface

Know it, and also know why

What is a PHP array?

Regarding this issue, the official document gives this explanation:

The array in PHP is actually an ordered map. Mapping is a
type of associating values ​​to keys . This type is optimized in many ways, so it can be regarded as a real array, or list (vector), hash table (an implementation of mapping), dictionary, collection, stack, queue and more possibilities. Since the value of an array element can also be another array, tree structures and multidimensional arrays are also allowed.

It is worth noting that it is different from static languages ​​such as JAVA and C. In PHP, it is not necessary to specify the size of the array and the type of data stored when initializing the array. This is not only the advantage of PHP, but also its disadvantage.

How are PHP arrays classified?

Generally, PHP array is generally divided into indexed arrays and associative array types.
Of course, you can also sort the array from other directions. As: according to the array dimensions may be divided into one-dimensional arrays and multidimensional arrays and the like.
From the definition of the array, we can know that the array is actually an ordered map of key-value pairs. This also means that each element in the array exists in the form of key => value. As each number is a key element in the array when the array is called then the array index ; the other hand, if the key is not the presence of an array of numbers called associative array

What are the ways to traverse the array?

1. for

The for loop is the most complex loop structure in PHP. Its behavior is similar to that of C language. The syntax of for loop is:

for (expr1; expr2; expr3)
statement The first expression (expr1) is unconditionally evaluated (and executed) once before the start of the loop.

expr2 is evaluated before the start of each loop. If the value is TRUE, the loop continues and the nested loop statement is executed. If the value is FALSE, the loop is terminated.

expr3 is evaluated (and executed) after each loop.

Each expression can be empty or include multiple expressions separated by commas. In the expression expr2, all expressions separated by commas will be calculated, but only the last result will be taken.

It is worth noting that: expr2 is empty means that the loop will continue indefinitely (like C, PHP implicitly thinks its value is TRUE). This may not be as useless as you think, because you often want to end the loop with a conditional break statement instead of using the for expression to determine the truth value. Such as:

$arr = ['a','b','c'];

for ($i = 0; ; $i++) {
    
    
    echo $arr[$i];
    if ($arr[$i] === 'c')
        break;
}

The for loop is a commonly used way to traverse arrays. It can easily traverse the array and manipulate each element of the array. A simple example:

$arr = ['a','b','c'];

for ($i = 0; $i < count($arr); $i++) {
    
    
    echo $arr[$i];
}

This way of writing may be the most common way of writing for coders who are just entering the line, but it may be bad (may cause slow execution). There is a problem. The count() function must be used to calculate the length of the array $arr in each loop. Since the length of the array is always the same, a better way is to store the length of the array as an intermediate variable first, instead of more Call count() times, as follows:

$arr = ['a','b','c'];

for ($i = 0, $len = count($arr); $i < $len; $i++) {
    
    
    echo $arr[$i];
}

In addition, PHP also supports an alternative syntax for for loops with colons.

$arr = ['a','b','c'];

for ($i = 0, $len = count($arr); $i < $len; $i++):
    echo $arr[$i];
endfor;

The for loop has a wide range of applications. It can be used for indexing arrays, associative arrays, and looping strings, etc...

$arr = [
    'a' => 'a',
    'b' => 'b',
    'c' => 'c'
];

//循环打印关联数组值
for ($i = 'a', $j = 0; $j <count($arr); $j++, $i = chr(ord($i) + 1) ) {
    
    
    echo $arr[$i];
}

$str = 'abcdefg';
//依次打印字符串元素
for ($i = 0, $len = strlen($str); $i < $len; $i++):
    echo $str[$i];
    echo "<hr/>";
endfor;
2. foreach

The foreach syntax structure provides a simple way to traverse an array.
foreach can only be applied to arrays and objects. If you try to apply to variables of other data types, or uninitialized variables, an error message will be issued. There are two syntaxes:
foreach (array_expression as $value)
statement

The first format of foreach (array_expression as $key => $value)
statement
traverses the given array_expression array. In each loop, the value of the current cell is assigned to $value and the pointer inside the array moves one step forward (so the next cell will be obtained in the next loop).

The second format does the same thing, except that the key name of the current unit is also assigned to the variable $key in each loop.

A simple example:

$arr = [
    'a' => 'a',
    'b' => 'b',
    'c' => 'c'
];

foreach ($arr as $value) {
    
    
    echo $value;
}  //只获取值

foreach ($arr as $key => $value) {
    
    
    echo $key;
    echo $value;
}  //获取键 和 值

PHP also supports an alternative syntax for foreach loops with colons.

foreach($array as $element):
  #do something
endforeach;

If you want to modify the elements of the array inside the foreach, you can easily modify the elements of the array by adding & before $value. This method will assign a value by reference instead of copying a value. E.g:

$arr = [
    'a' => 'a',
    'b' => 'b',
    'c' => 'c'
];

foreach ($arr as &$value) {
    
    
    $value = $value.'zzz';
}  //只获取值

var_dump($arr); //array(3) { ["a"]=> string(4) "azzz" ["b"]=> string(4) "bzzz" ["c"]=> &string(4) "czzz" }

It should be noted here that the reference of $value is only available when the traversed array can be referenced (for example, a variable). The following code cannot run:

foreach (array(1, 2, 3, 4) as &$value) {
    
    
    $value = $value * 2;
}


The $value reference of the last element of *Warning array will be retained after the foreach loop. It is recommended to use unset() to destroy it. Because it is very easy to cause some problems, such as: strange problems caused by foreach

Note:
When foreach starts to execute, the pointer inside the array will automatically point to the first unit. This means there is no need to call reset() before the foreach loop.
Since foreach relies on the internal array pointer, modifying its value in the loop may cause unexpected behavior.
foreach does not support the ability to use "@" to suppress error messages.

Foreach to traverse objects
It is worth mentioning that foreach can only traverse visible properties, which means that using foreach outside the object can only access public type properties. If you need to traverse the attributes of the protected type, you need to define methods in this class or its subclasses to use foreach. The traversal of private attributes must be performed in its own class.

3. Use list(), each() to traverse the array

The functions involved are:
list() : Assign the values ​​in the array to a set of variables [Like array(), this is not a real function, but a language structure]
each() : Returns the current key/value in the array Right and move the array pointer forward one step
reset : Point the internal pointer of the array to the first unit, and return the value of the first unit of the array, or FALSE if the array is empty.

Examples are as follows:

$arr = [
    'ak' => 'av',
    'bk' => 'bv',
    'ck' => 'cv'
];
reset($arr);  //开始循环之前,需调用此函数将数组内部指针指向第一个单元。避免指针为指向第一个单元,造成数组循环不全或循环失败的情况
while (list($k, $v) = each($arr)) {
    
    
    echo $k.'=>'.$v;
    echo "<hr/>";
}

Things worth noting:

1. Since PHP7.2.0, each() function has been deprecated. This function is highly deprecated. [If called in PHP 7.3.4 version, it will return an error (Deprecated: The each() function is deprecated. This message will be suppressed on further calls in …)]
2. In PHP 5, list() starts from the rightmost Parameter assignment starts; in PHP 7, list() assigns values ​​from the leftmost parameter. If you use pure variables, don't worry about this. But if you use an indexed array, you usually expect the result to
be from left to right as written in list() , but it is not actually in PHP 5, it is assigned in the reverse order.
Generally speaking, it is not recommended to rely on the order of operations, which may be modified again in the future.

4. Use array pointers to traverse the array

The functions involved are:
reset : Point the internal pointer of the array to the first unit, and return the value of the first unit of the array, or FALSE if the array is empty.

key() : The function returns the key name of the current unit pointed to by the internal pointer in the array. But it will not move the pointer. If the internal pointer exceeds the end of the element list, or the array is empty, this function returns NULL.

current() : The current() function returns the value of the array element currently pointed to by the internal pointer without moving the pointer. If the internal pointer points beyond the end of the unit list, current() returns FALSE. [It is worth noting that if the value of an element of the array is equal to (bool) false, this function will also return FALSE, so this function cannot be used to determine whether the end of the array is reached]

next() : next() and current() behave similarly, with only one difference, moving the internal pointer forward one bit before returning the value. This means that it returns the value of the next array element and moves the array pointer forward by one. [Similarly, if the value of an element of the array is equal to (bool) false, this function will also return FALSE, so this function cannot be used to determine whether the end of the array is reached]

$arr = [
    'ak' => 'av',
    'false' => false,
    false => 'cv'
];

while (true) {
    
    
    $k  = key($arr);
    if (!isset($k)) {
    
    
        reset($arr); //结束之前应将数组内部指针指向第一个单元
        unset($k);
        break;
    }
    echo $k.'=>'.current($arr);
    echo '<hr/>';
    next($arr);
}

Some things worth noting:

1$arr[true] 等价于 $arr[1]$arr[false] 等价于 $arr[0]2、使null做为键名,相当于创建或覆盖一个$arr[null],可以使用$arr[null]$arr[""]来访问。

3、使用带小数点的数字作为键名时,键名会自动截取整数部分作为键名。如$arr[123.45]=5,你使用$arr[123.45]$arr[123]均可以取得键值;用foreach遍历时,使用的是$arr[123]4$arr[]=5,会在数组$arr后面添加上该元素。

Guess you like

Origin blog.csdn.net/weixin_39815001/article/details/107730321