why is foreach loop required n why it is used for only array ?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

why is foreach loop required n why it is used for only array ??

25th Jul 2016, 6:08 AM
sagar
sagar - avatar
4 Answers
+ 4
What is the difference between While and For loop? They do just one thing: Repeat a code or a block of a code for many times; But in For, you now that how many do your codes may run while in While loop usually you don't know that when the loop will end (Also you can do what For loop do with While loop, and so on). The difference between For and Foreach loop is like that difference; they do a same work, but Foreach loop has created for arrays to do easier works with them. Don't forget that some codes created just for better coding and easier programming; like functions.
25th Jul 2016, 8:48 AM
$machitgarha
$machitgarha - avatar
+ 3
foreach loop is used when you dont know about the total number of array members especially if array is associative array provided that you want to loop through all members. it also makes it easy where you also want to use key in the form of key value pair.. foreach loop can also be used for objects.
3rd Nov 2016, 8:18 PM
Motsim
Motsim - avatar
+ 1
Foreach loop is used basically for traversing, this means if we want to display or want to access each element in array at once, then we use foreach loop, where pointer from index 0 to lenght.n will access each element.
7th Jan 2017, 7:20 AM
Javed Saifi
Javed Saifi - avatar
0
foreach helps in accessing all elements.. thats all
17th Jul 2017, 12:29 PM
sagar
sagar - avatar