Pages

Wednesday, October 2, 2013

Exploring the PHP Control Structures Part 1

Written by: Lorenzo D. Alipio  

Remember in previous section "Introduction to PHP Syntax"?, I was able to list the following, but I did not discuss them any further. In this section, we will be exploring the most common control structures of PHP.

What is control structures really? What can they do to improve our program? Or, better yet what are their roles in writing PHP applications?

The easiest way to remember what control structures can do is that, they can control the application's response to any given events as they are defined in our application. This statement is true, because if we don't have any instructions on how the application is going to handle the user's response or events, our application cannot interact with our user. Let us write a simple code in PHP that will say something when the day of the week is Wednesday. Codes below demonstrate the if/else statements in PHP.


<?php

$today = date("l");

if($today === "Wednesday"){

echo "Today is ". $today ;

}

else{

echo "Today is not Wednesday";

}



?>

Codes above should output "Today is Wednesday", every Wednesdays of the week. Otherwise, it will output "Today is not Wednesday".

Let's add else if into the mix, and let make it echo "Today is Thursday" if $today is equal to Thursday.

<?php

$today = date("l");

if($today === "Wednesday"){

echo "Today is ". $today ;

}
else if($today ==="Thursday"){
echo "Today is ". $today;
}
else{

echo "Today is not Wednesday or Thursday";

}

?>


Noticed, how we set our rules in our simple application above? We set rules that only if Wednesday we echo the name day, and else if Thursday we also want to echo the name of the day. By using our simple example above, we can set many rules within our application.

Alternatively, we can use PHP switch statement instead of if/else/elseif statements. Below is a sample code equivalent to the code above.

<?php


$today = date("l");

switch ($today){

case 'Wednesday':

echo "Today is ". $today ;

break;

case 'Thursday':

echo "Today is ". $today ;

break;

default:
echo "Today is not Wednesday or Thursday";

}

?>

Another alternative is similar to a short-hand syntax. Please consider the codes below. It should return the same result as the above example codes.

<?php
$today = date("l");

echo (($today ==='Wednesday')? 'Today is'. $today : (($today ==='Thursday')? 'Today is'. $today : 'Today is not Wednesday or Thursday'));

?>

This conclude the tutorial Control Structures Part 1. Please come for the tutorial on loops on Control Structures Part 2.

No comments:

Post a Comment