The following small series will bring you an in-depth understanding of Array and foreach in PHP. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the small series. 1. understand the array.
Arrays in PHP are actually an ordered ING. Valuing is a type that associates values with keys. For more information, see Array in PHP.net.
2. example: a general array
Here, I use a simple example and use the graphical method to understand arrays.
$a = array(3 => 'a', 1 => 'b', 2 => 'c'); echo var_dump($a);
[Note]: use arrows to describe the data values of each unit in array $ a corresponding to a memory address (in fact, its internal structure adopts the HashTable structure, refer to the Hash algorithm in PHP written by laruence ).
3. example: add a reference to the array definition.
$x = 'x';$a = array(3 => 'a', 1 => &$x, 2 => 'c'); echo "";echo var_dump($a); $x = 'y';echo var_dump($a);
$ A [1] and $ x correspond to the same data. when var_dump ($ a) is used, multiple & symbols (& string (1) "x") of the array's 2nd units are displayed, indicating reference.
When you change the value of $ x to 'y', it is equivalent to modifying the value of $ a [1] to 'y '.
You can clearly describe this change:
4. example: use foreach to traverse the array.
$a = array(3 => 'a', 1 => 'b', 2 => 'c'); echo "";foreach ($a as $key => $value) { echo "$key => $value
"; }
[Note:] The gray virtual arrow indicates giving a value.
5. example: use the reference value assignment in the foreach traversal array.
$a = array(3 => 'a', 1 => 'b', 2 => 'c'); echo "";foreach ($a as $key => &$value) { $value.='n'; echo "$key => $value
"; }
6. example: further analysis of Example 5.
In example 5, after foreach traverses the array, the $ value variable is not automatically destroyed, pointing to the same data as the last unit $ a [2] of array $.
At this time, the value of $ value is changed, that is, the value of $ a [2] is changed.
$value='m'; echo "";echo "\$value=$value
";echo var_dump($a);
Instance verification. The $ value reference of the last element of the array is retained after the foreach loop. We recommend that you use unset () to destroy it.
7. Summary
The above example only describes some features of array and foreach in php. Finally, I feel that the array and foreach in php are different from other programming languages. PHP cannot be analyzed using a structure similar to the C language.
The above is a small series of in-depth understanding of all the Array and foreach content in PHP. I hope you can support the first PHP community ~
For more information about Array and foreach in PHP, see The PHP Chinese website!