Tuesday, 28 June, 2022


Webmaster Tools

single post

  • Home
  • PHP control structures

PHP control structures

if, while, for and other control structures


The main PHP control structures are: if, while, for and others. Well, let’s take a look at some of them:


The if construct is used in almost every programming language, PHP too. Let’s take an example:

if ($var1 > $var2) {
print “$var1 is greater than $var2”;

Our script will execute (print) the statement $var1 is greater than $var2 if the expression $var1 > $var2 is TRUE. If it’s FALSE – the statement will be ignored.

You can write the above piece of script using an alternative syntax if you prefer:

if ($var1 > $var2) :
print “$var1 is greater than $var2”;

You can also include elseif and else structures in your if control structures:

if ($var1 > $var2) :
print “$var1 is greater than $var2”;
else :
print “$var1 is not greater than $var2”;

We hope that you can figure out yourself how the script will execute in this case.


An example:

$var1 = 3;
$var2 = 0;
while ($var1 > $var2) {
print “$var2”;

The script will execute the statement (print the $var2 and increment it by one) repeatedly, as long as the expression $var1 > $var2 evaluates to TRUE. You can also use the alternate syntax: while (…) : … endwhile;


An example:

for ($var1 = 1; $var1 < 3; $var1++) {
print “$var1”;

The expression $var1 < 3 is evaluated and if it evaluates to TRUE, the statement (print $var1) is executed. At the end of each iteration, the $var1++ is executed.

There are also other control structures, like: foreach, do … while, continue, break, switch

Well, let’s go to the next tutorial PHP functions.

Recent Comments

No comments to show.