PHP Loops

Programming

Various Types of PHP Loops

Why we use PHP loops because sometimes when you write code you want a certain number of times to run the same block of code again and again. So we can use loops instead of adding many nearly identical code-lines to a file. Loops are used to repeatedly execute the same block of code, as long as a certain condition is met. To save time and energy, the basic concept behind a loop is to automate the repetitive tasks within a program. PHP supports four types of loops.

while – Loops through a code block as long as the specified condition evaluates to true.

do…while – Loops once through a block of code, then repeats the loop as long as the condition is valid.

foreach – Loops for every element in an array by block of code.

for – Loops through a block of code until a specified number is reached by the counter.

PHP loops

while loop :
The while statement will loop through a block of code as long as it evaluates to true the condition defined in the while state. If the check expression is valid then execute the code block. Upon execution of the code, the test expression will be tested again and the loop will continue until the test expression is found to be incorrect.

Syntax :

while (condition) {
// block of code to be executed
}

do…while loop :
The do…while loop will always execute the code block once, then test the condition and repeat the loop while the condition you define is true.

Syntax :

do {
// block of code to be executed
}
while (condition);

foreach loop :
The foreach loop operates for an array, which is used in an array to loop through any key/value pair.

Syntax :

foreach (array as value) {
// block of code to be executed
}

for loop :
The for loop repeats a block of code as long as it satisfies a certain condition. Usually, it is used to execute a block of code for any amount of times. It is used if you know how many times a statement or a sequence of statements you want to execute.

Syntax :

for(initialization; condition; iterative){
// block of code to be executed
}