الاثنين، 14 مارس 2011

If & while & for Statements

if statement
Use the if statement to execute some code only if a specified condition is true.

Syntax

if (condition) code to be executed if condition is true;

The following example will output "Have a nice weekend!" if the current day is Friday:

<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>

The if...else Statement
Use the if....else statement to execute some code if a condition is true and another code if a condition is false.

Syntax

<?php
$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
else
  echo "Have a nice day!";
?>

 

The if...elseif....else Statement

Syntax

<?php
$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
elseif ($d=="Sun")
  echo "Have a nice Sunday!";
else
  echo "Have a nice day!";
?>

_______________________________________________________________

The while Loop

The while loop executes a block of code while a condition is true.

Syntax

 while (condition)
  {
  code to be executed;
  }

Example

<?php
$i=1;
while($i<=5)
     {
        echo "The number is " . $i . "<br />";
        $i++;
      }
?>
Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5 
The do...while Statement

<?php
$i=1;
do
  {
  $i++;
  echo "The number is " . $i . "<br />";
  }
while ($i<=5);
?>

Output:

The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

_______________________________________________________________

The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

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

Example

<?php
for ($i=1; $i<=5; $i++)
  {
  echo "The number is " . $i . "<br />";
  }
?>

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

The foreach Loop

The foreach loop is used to loop through arrays.

Syntax

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

 

Example

<?php
$x=array("one","two","three");
foreach ($x as $value)
  {
  echo $value . "<br />";
  }
?>

Output:

one
two
three

ليست هناك تعليقات:

إرسال تعليق