PHP Loops (PHPL)

PHP looping is used to execute a block of code/program several times (a certain number of times).

In a loop, it generally consists of 3 components, namely: 

  1. Initial Value/Initialization, namely determining the initial value in the loop
  2. Loop Conditions, if the value meets certain conditions, the loop will continue, otherwise the loop will be stopped.
  3. Value Changer, during the loop the value will be changed continuously.

Note!: Before the loop is run, you need to know first when the program / loop / loop will stop / be stopped. Otherwise, your computer will experience Deadlock / Hang-up.

Syntax

for (init counter; test counter; increment counter) {
    code to be executed;
}

Example 1

<?php
 $a=1;
 while($a<=15)
 {
  echo("Ini no ke-$a<br>");
  $a++;
 }
?>

See the results -> 

Ini no ke-1
Ini no ke-2
Ini no ke-3
Ini no ke-4
Ini no ke-5
Ini no ke-6
Ini no ke-7
Ini no ke-8
Ini no ke-9
Ini no ke-10
Ini no ke-11
Ini no ke-12
Ini no ke-13
Ini no ke-14
Ini no ke-15

Example 2

<?php
 for ($i=1;$i<=15;$i++)
 {
 //$i=1 >>> Nilai awal perulangan
 //$i<=15 >>>kondisi syarat perulangan
 //$i++ >>> pengontrol variabel perulangannya
 echo("<font size=$i>$i</font><br>");
 }
?>

See the results -> 

PHP foreach loop

The foreach loop only works on arrays, and is used to traverse each key/value pair in an array.

Each iteration (1x) of the loop, the array value is assigned (remember the assignment operator!) to $value (the name of the free variable!), while the array pointer moves once until it reaches the last element.

Each pointer (key/address) indicates the value of each element.

Here I will not repeat the discussion about arrays. If you still do not understand the concept of arrays, please understand it first here:

Syntax

foreach ($array as $value) {
    code to be executed;
}

Example

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
  echo "$value <br>";
}
?>

See the results -> 

red
green
blue
yellow

Post a Comment

Previous Next

نموذج الاتصال