Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Loops
- To do repetitive tasks.
- To run block of code certain time until condition meets.
- Types of Loops
- 1. While Loop
- Loops through a block of code until condition is evaluated to true.
- 2. Do While Loop
- The block of code executed once and then condition is evaluated. If condition is true, the statement is repeated as long as the specified condition is true
- 3. For Loop
- Loops through a block of code until the counter reaches a specified number
- 4. Foreach Loop
- Loops through a block of code for each element in an array.
- */
- // PHP WHILE LOOP
- // Syntax
- // while (condition) {
- // code to be executed
- // }
- $i = 1;
- while ($i <= 3) {
- echo $i . '<br />';
- $i++;
- }
- echo '<br /><br /><br />';
- /* PHP DO WHILE LOOP
- Syntax:
- do {
- code to be executed
- }
- while (condition)
- */
- $i = 1;
- do {
- echo $i . '<br />';
- $i++;
- }
- while ($i <= 10);
- echo '<br /><br /><br />';
- /*
- FOR LOOP
- Syntax:
- for (initialization; condition; increment) {
- code to be executed
- }
- */
- for ($i = 10; $i >= 1; $i--) {
- echo 'The number is ' . $i . '<br />';
- }
- echo '<br /><br /><br />';
- /* FOREACH LOOP
- syntax:
- indexed array
- foreach ($array as $value) {
- code to be executed
- }
- associative array
- foreach $array as $key => $value) {
- code to be executed
- }
- */
- $colors = array('Green', 'Blue', 'Red', 'White', 'Orange');
- foreach ($colors as $color) {
- echo 'The color is ' . $color . '<br />';
- }
- echo '<br /><br /><br />';
- $superhero = array(
- 'name' => 'Peter Parker',
- 'email' => 'peterparker@gmail.com',
- 'age' => 48
- );
- foreach ($superhero as $key => $value) {
- echo $key . ' : ' . $value . '<br />';
- }
- echo '<br /><br /><br />';
- $superhero = array(
- 'spider-name' => array(
- 'name' => 'Clark Kent',
- 'email' => 'clarkkent@gmail.com'
- ),
- 'super-man' => array(
- 'name' => 'Peter Parker',
- 'email' => 'peterparker@gmail.com'
- ),
- 'iron-man' => array(
- 'name' => 'Harry Potter',
- 'email' => 'harrypotter@gmail.com'
- )
- );
- $keys = array_keys($superhero);
- for ($i = 0; $i < count($superhero); $i++) {
- echo $keys[$i] . '{<br />';
- foreach($superhero[$keys[$i]] as $key => $value) {
- echo $key . ' : ' . $value . '<br />';
- }
- echo '}<br />';
- }
- $i = 0;
- echo $i;
- $i++
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement