+ 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🙃

12th May 2020, 6:57 AM
Mahdee Mohammad
Mahdee Mohammad - avatar
4 Respuestas
+ 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
12th May 2020, 7:12 AM
Ipang
+ 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
12th May 2020, 6:58 AM
Ahmed
Ahmed - avatar
+ 4
forEach can be used for adding property to an array of objects too https://code.sololearn.com/Wu1u667O26li/?ref=app
15th May 2020, 2:17 AM
Calviղ
Calviղ - avatar
+ 1
Ipang that was a wonderful example :) ❤️🐎
12th May 2020, 7:45 AM
Tibor Santa
Tibor Santa - avatar