Wednesday, September 18, 2013

Loops in PHP

Introduction to Loops in PHP

Using Loops in PHP

Loops are an vital part of a programming language. Typically the need to use loops in a program occur when you want to execute a piece of code repeatedly until a desired condition is achieved. There are many control structures that can be use to implement looping in a program.

The While loop

The while loop is one is the simplest looping control structure in PHP. When you specify a condition and a code block along with the while loop, the code block is repeatedly execute until the condition becomes false.

<?php
$a = 1;
while ($a <= 10){
  echo $a ."<br/>";
}
?>

The for loop

The for loop is similar to the while loop and can achieve the same result. It is use to evaluate a set of conditional expression at the beginning of each loop. The for loop is one of the most complex loop in PHP.

<?php
for ($a=1; $a <=10 ; $a++){
  echo $a ."<br/>";
}
?>


Breaking a loop

Sometimes, you might want to break a loop before it complete execution .The break statement can do this.

<?php
for ($a=1; $a <=10 ; $a++){
echo $a ."<br/>";
  if($a==5){
    break;
  }
}
?>

The continue statement

The continue statement is the reverse  the break statement, doesn't breaks a loop. When you break a loop the loop with the break statement, you can't check for the same condition again. The continue statement just skip the specific iteration and doesn't cause the loop to end.

<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
  echo $i;
}
?>

The output will be: 2.

Nesting loops

Nesting loops are a way to use a loop statement within another statement. for example, if you have a loop x, and have another loop y in the loop y in the loop x, the loop y will be executed x*y.

<?php
for ($a =10; $a <= 15; $a++){
    echo "First Loop <br/>";
       for ($b = 5; $b < 10; $b++){
           echo "Second Loop <br/>";
       }
}
?>

Tuesday, September 17, 2013

PHP function to get age for date of birth

 PHP function to get age for date of birth  
 
function age_from_dob($dob){
 
$dob = strtotime($dob);
$y = date('Y', $dob);
 if (($m = (date('m') - date('m', $dob))) < 0) {
  $y++;
 } elseif ($m == 0 && date('d') - date('d', $dob) < 0) {
  $y++;
 }
return date('Y') - $y;
 } 
 
 
 
 echo age_from_dob('2005/04/19'); date in yyyy/mm/dd format.

Labels

AJAX (1) Answers (1) Apache (1) Array (16) bug (1) C (1) C++ (1) Calendar (1) Class (1) Commands (1) Cookies (2) Database (2) Date (7) Days (1) explode (1) File Upload (1) FILES (1) firewall (1) fix (1) Functions (26) GET (1) GMT (1) JavaScript (2) localhost (1) Mail (1) Menu (1) MYSQL (13) PERL (1) PHP (36) php.ini (1) POST (1) preg_match (1) Questions (1) Script (1) SMS (2) Solution (1) String (1) Time (5) Time Zone (1) Vista (1) Wamp Server (1) windows 7 (2) XML (1)

Popular Posts

Popular Posts