hassan Posted August 6, 2015 Share Posted August 6, 2015 Hi On page 70 it discusses loops and states "The functionality of both loops is similar enough that for and while can often be used interchangeably. Still, experience will reveal that the for loop is a better choice for doing something a known number of times, whereas while is used when a condition will be true an unknown number of times." I understand that the foreach loop will get everything in an array. Where and when and why would you use a for loop instead of a while and vice-versa? (can someone give practical scenarios)? Also where and when and why would you use a do while loop? what benefits does it have instead of using foreach or for or while loops? Thanks in advance Link to comment Share on other sites More sharing options...
Larry Posted August 7, 2015 Share Posted August 7, 2015 If you keep reading the book you'll see more and more examples, but the rule is the one you quoted: the for loop is a better choice for doing something a known number of times, whereas while is used when a condition will be true an unknown number of times So the while loop is normally used for reading through database query results, files, and network communications. The for loop and/or foreach, is used to iterate a known number of times, such as on an array. Link to comment Share on other sites More sharing options...
hassan Posted August 7, 2015 Author Share Posted August 7, 2015 Ok thinking a bit more about it ... would we use the for loop for example when we want to display ten items from a data base and create mulitple pages showing ten items? like in a product catalog? Link to comment Share on other sites More sharing options...
Larry Posted August 8, 2015 Share Posted August 8, 2015 If you keep reading, you'll see more examples. But to answer your specific question, no, to limit the number of database records shown--to implement pagination, you'd still use a while loop, but limit your query to only returning X records from the database. Link to comment Share on other sites More sharing options...
hassan Posted August 20, 2015 Author Share Posted August 20, 2015 Thanks :-) Link to comment Share on other sites More sharing options...
Recommended Posts