+ 3
Please explain the foreach loop.
It seems a bit difficult to me to understand the foreach loop in PHP. The explanation given in the course seems to be hard. I will be very glad if you explain it to me in an easier or different way. Thanl u🙃
4 ответов
+ 6
Pretend we have ten horses in a stable, and we want to vaccinate the horses with something. In such cases you may say,
For each (horse) in the stable
Vaccinate (horse)
Here, you say "horse", but actually, which horse you referred to, will be different each time. It's not like you would vaccinate a horse twice, or worse ten times (the count of horses).
You can think of the stable as an array, and the horses as the elements of the array (the content of the array).
Hth, cmiiw
+ 5
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
+ 4
forEach can be used for adding property to an array of objects too
https://code.sololearn.com/Wu1u667O26li/?ref=app
+ 1
Ipang that was a wonderful example :)
❤️🐎