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?
- if
- else
- elseif/else if
- while
- do-while
- for
- foreach
- break
- continue
- switch
- declare
- return
- require
- include
- require_once
- include_once
- goto
<?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