php foreach usage is: foreach can only be used for arrays. When trying to use it for other data types or an uninitialized variable, an error will occur. The format is [foreach (array name as subscript => ;value)】.
php foreach usage is:
Simply put foreach
its format is like this foreach (array name as subscript => value)
The subscript is the $a[1] above, and the 1 here is the subscript of the array!
At this point you should understand why $a[$key] is output like this
You remember that no matter how you change it, the output method of the array will always be $a[1], it won’t It is $a['language']
foreach() has two uses:
1: foreach(array_name as $value){ statement; }
The array_name here is the name of the array you want to traverse. In each loop, the current element of the array_name array The value is assigned to $value, and the subscript inside the array moves down one step, that is, the next element is obtained in the next loop.
2:foreach(array_name as $key => $value){ statement; }
The difference between this and the first method is that there is an extra $key, that is, in addition to assigning the value of the current element to $value, the key value of the current element will also be assigned in each loop. Give the variable $key. The key value can be a subscript value or a string. For example, "0" in book[0]=1, "id" in book[id]="001".
Related free learning recommendations:php programming( video)
The above is the detailed content of What is the usage of php foreach. For more information, please follow other related articles on the PHP Chinese website!