// This example skips the value of 2
for ($a = 0; $a < 4; $a++) {
if ($a == 2) {
continue;
}
echo "The number is: $a \n";
}
/* outputs: The number is: 0
The number is: 1
The number is: 3
*/
// We print array elements by omitting "Audi".
$cars = array("BMW","Audi","Porsche");
foreach ($cars as $val) {
if ($val == "Audi") {
continue;
}
echo "$val \n";
}
/* outputs: BMW
Porsche
*/
// This example jumps out of the loop when a is equal to 5:
for ($a = 0; $a <= 10; $a++) {
if ($a == 5) {
break;
}
echo "The number is: $a \n";
}
/* outputs: The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
*/
// We print the elements of the array until the value is equal to "Audi".
$cars = array("BMW","Porsche","Audi","Mercedes-Benz");
foreach ($cars as $val) {
if ($val == "Audi") {
break;
}
echo "$val \n";
}
/* outputs: BMW
Porsche
*/
foreach ($array as $value) {
code to be executed;
}
For instance:
// array - $country
$country = ["Georia","Ukraine","Spain"];
foreach ($country as $value) { // Instead of name $value we can write any name
echo "$value \n";
}
/* outputs: Georia
Ukraine
Spain
*/
// array - numbers
$numbers = array("one" => 1 , "two" => 2 , "three" => 3 );
foreach($numbers as $n => $value) {
echo "$n = $value \n";
}
/*outputs: one = 1
two = 2
three = 3
*/
// also, we can print only keys/values
foreach($numbers as $n => $value){
echo "$n \n"; // if we need value of key, we must whrite $value
} // keys are "one","two","three" and values are 1,2,3
/*outputs: one
two
three
*/
$str = "Hello world";
print_r (explode(" ",$str));
Return:
Array ( [0] => Hello [1] => world )
The code will return a string containing the elements of the array.
$arr = array('Hello','World!');
echo implode(" ",$arr);
Return:
Hello World!
<?php
for ($i=1;$i<=50;$i++) {
echo "$i ";
if ($i%5==0) {
echo "\n";
}
}
?>
<?php
$today =(date'z');
if ($today==1) {
echo "დღეს არის წლის $today-ლი დღე";
}
elseif ($today>=2 and $today<=20) {
echo "დღეს არის წლის მე-$today დღე";
}else
echo "დღეს არის წლის $today-ე დღე";
?>
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
The PHP while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}
`