PHP / PHP LoopsIt you want to run a particular block of code repeatedly we will go for using a concept of loops.PHP looping statements: 1. while loop. 2. do while loop. 3. for loop. 4. foreach loops through a block of code for each element in an array PHP while Loop It will execute the block of code till the condition is true and come out of the block when the condition if false. Syntax while (condition is true) { Executes block/ line/ lines of code if one condition is true. } PHP while Loop It will execute the block of code till the condition is true and come out of the block when the condition if false. Syntax while (condition is true) { Executes block/ line/ lines of code if one condition is true. }
do...while Loop It will execute the block of code once and then it will check the condition to run the block of code or not depends on the condition is true otherwise it will come out of the loop. Syntax do { Executes block/ line/ lines of code if one condition is true. } while (condition is true);
PHP for Loop It is used to run the block of code for a specified number of times. Syntax for (initialization of variables; test variables; increment / Decrement variables) { Executes block/ line/ lines of code if one condition is true. } Initialization of variables: Initialization is Used to give start values for the variables. Test variables: A variable are tested and if it is true executes the block of code otherwise comes out of the loop. Increment / Decrement variables: This section is used to increment / Decrement the variable values.
PHP foreach Loop It is used to work with arrays, and is used to loop through each key/value pair in an array. Syntax foreach ($array as $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.
|