Conditional statements are used to
perform different actions for different conditions. In PHP we have the
following conditional statements:
- if statement –
executes some code if one condition is true
- if…else statement –
executes some code if a condition is true and another code if that
condition is false
- if…elseif…else statement –
executes different codes for more than two conditions
- switch statement –
selects one of many blocks of code to be executed
The
if Statement
The if statement executes some code
if one condition is true.
The
if…else Statement
The if…else statement executes some
code if a condition is true and another code if that condition is false.
The
if…elseif…else Statement
The if…elseif…else statement
executes different codes for more than two conditions.
The Switch Statement
The switch statement is used to
perform different actions based on different conditions. It is used to select
one of many blocks of code to be executed.
PHP Loops
When we write a code, we want the
same block of code to run over and over again in a row. Instead of adding
several almost equal code-lines in a script, we can use loops to
perform the same task. In this PHP Tutorial we will learn about the three
looping statements.
In PHP, we have the following
looping statements:
- while –
loops through a block of code as long as the specified condition is true
- do…while –
loops through a block of code once, and then repeats the loop as long as
the specified condition is true
- for –
loops through a block of code a specified number of times
The
While Loop
The while loop executes a block of
code as long as the specified condition is true.
The
do..while Loop
The do…while loop will always
execute the block of code once, it will then check the condition, and repeat
the loop while the specified condition is true.
PHP for loops execute a block of
code a specified number of times. It is used when you know in advance how many
times the script should run.
Now that you have learnt about the
Conditional Statements and Loops in PHP, let’s move ahead with the PHP Tutorial
and learn about the Functions in PHP.
foreach Loop
The
foreach statement is used to loop through arrays. For each pass the value of
the current array element is assigned to $value and the array pointer is moved
by one and in the next pass
next element will be processed.
Syntax
foreach (array as value)
{
code to be executed;
}
example of foreach loop
<?php $fruits = array("mango", "apple", "papaya", "lichi"); // foreach loop structure foreach ($fruits as $value) { echo "$value \n"; } ?>
|