What is the usage of php foreach

coldplay.xixi
Release: 2023-03-07 08:18:01
Original
4420 people have browsed it

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)】.

What is the usage of php foreach

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; }
Copy after login

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; }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!