Wednesday, April 13, 2016

Loops

Loops are a very powerful tool in PHP. Today, I will explain the different types briefly as an overview. There are some basic loops in PHP that are very similar to the three basic loops in Java in addition to a new one:

  • while
  • do...while
  • for
  • foreach
The first three loops perform the same as they do in Java, so it makes it easier for beginner developers to switch from one language to the other. Because of the familiarity, I will be brief in my explanations for these loops.

The while loop is for when the developer wants to perform an action if the condition is true. If not, then the code will be skipped over.

A do...while loop is for when the developer wants to perform an action at least once while the condition is true. 

A for loop is usually for when the developer has a set amount of times that the section of code should be looped. This loop is more efficient than the others because it can initialize, compare, and modify a variable all in one line.

A foreach loop is the new addition that is not in Java! This loop takes each element in an array, sets it to a variable, and performs an action on it. After that, the pointer will move to the next element and continue from there. To help explain this concept further, watch the video below:




Source: http://www.tutorialspoint.com/php/php_loop_types.htm

1 comment:

  1. I love me some loops. If you can get the hang of them, they will save you some serious time. Just earlier today, in operating systems, we wrote a program that outputted 2,000,000 lines using simple loop. Great post! Here is my blog: http://bitsbotsandbobby.blogspot.com/

    ReplyDelete