control structures in php

Sharing is caring!

Control Structures

Control Structures are loops, like for, and conditionals, such as if. Most of these will be familiar to the javascript programmer, and this page is basically a list. The following exist in php:

if and else

These are exactly the same as javascript and other languages.

if ($a==$b) {

print “The same”;

}

else {

print “They aren’t the same”;

}

There is an alternative way of writing the if statement. For instance:

<script type=“text/javascript”>

<?php
$a=5;
if(
$a==5):?>alert(“It’s five!”);
<?php
endif;
?>

//result: alert saying “It’s five”

</script>

The condition, if ($a==5) is followed by a colon (:), and the end of the block of statements is followed by endif (in php tags). In this way, the statement is not php, and in this case it is javascript.

In the alternative styles, instead of having two curly brackets {} the code replaces the first with a colon and the last with an end… in the case of if, it is endif. In other cases, endwhile, endfor, etc.

If there are other conditions, such as ifelse, then this new condition acts as the closing curly bracket for the if-statement, and the the endif, at the end of the block of code, acts as the final bracket. For instance:

if($a==5): //note colon
print”a equals 5″;
print”…”;
elseif($a==6): // the elseif effectively ends the if-statement and replaces a }
//note the colon after ifelse(…)!
print”a equals 6″;
print”!!!”;
else : //This acts as the end bracket } for the elseif
print”a is neither 5 nor 6″;
endif; // The endif acts as the final curly bracket for the BLOCK of statements

Below is a more complex example:

<script type=“text/javascript”>

<?php

$a=6;

if($a==5): //note colon

?>

document.write(“It’s five!”) ;

<?php

elseif($a==6): //colon!

?>

document.write(“It’s six!”);

<?php

else:

?>

document.write(“It’s neither six nor five”);

<?php

endif;

//result: It’s six!

?>

</script>

Fundamentally, you can put elseif within the if block between the colon (:) and endif;

elseif

elseif, which you can also write else if, gives you a second if-statement. The first if-condition, if met, is run, and any other elseif conditions, even if met are not run. So in the example below, the if-statement is met, so the program outputs Hello Tom, and not Hello Tom 2, even though the relevant elseif condition has been met. That is, elseif acts like a switch, and the control structure is exited at the first match.

$a=“Tom”;

if($a==“Tom”){

print“Hello Tom”;}

elseif($a==“Beryl”){

print“Hello Beryl”;

}

else if ($a==“Tom”){

print “Hello Tom 2”;

}

else {

print“I don’t know you!”;

}

//result: Hello Tom

while

The while loop is the same as in javascript:

$i=1;

while ($i<10){

print “Hello”;

$i++;

}

Ensure the while loop will exit! Forgetting $i++ means it will go on until the browser gets bored!

The next example uses the alternative style:

<?php

$i=1;

while($i<=10): //note the colon!

?>

Hello

<?php

$i++;

endwhile; // tells php the while is done

//result: HelloHelloHelloHelloHelloHelloHelloHelloHelloHello

?>

In the alternative style, the first bracket { is replaced with a colon: the final curly bracket } is replaced with endwhile.

do..while

The do..while loop is similar to the while loop, however, the while loop will not run if the condition is not met. The do..while loop, on the contrary, will always run at least once.

In the example below, the do..while loop runs once, even though the condition is never met (1 isn’t bigger than 100):

$i=0;

do{

print “The number is $i”;

}

while($i>100);

//result: The number is 0

for

The for loop is the same as javascript’s:

for($i=1;$i<=2;$i++){

print “This is $i<br>”;

}

//This is 1

//This is 2

The for loop can be written in various ways. One additional way is as follows:

for($i=1;$i<=3;print “This time it’s $i “,$i++);

//result: This time it’s 1 This time it’s 2 This time it’s 3

Quite neat isn’t it?

foreach

This is used to access the items in an array. For instance:

$arr=array(“cat”,“dog”,“aadvark”);

foreach($arr as $value){

echo“Value: $value<br>\n;

//Value: cat
//Value: dog
//Value: aadvark

This example shows the keys and values of an associative array:

$a=array(“fruit”=>“apple”,“meat”=>“ardvaak”,“vegetables”=>“potatoes”,“sweet”=>“pecan pie”);

foreach($a as $k=>$v){

print“\$a[$k]=>$v.\n;

};

//result: $a[fruit]=>apple. $a[meat]=>ardvaak. $a[vegetables]=>potatoes. $a[sweet]=>pecan pie.

break and continue

Break and continue are familiar to javascript programmers. Break exits a for, while, or switch structure. And continue exits the current pass in the loop and begins with the next. You can determine how many loops to break out of, or to continue from.

switch

The switch statement is also the same as the one in javascript. A switch statement will continue to, in the example below, print all the statements after finding one that is true, so breaks are used to prevent this. Each statement is followed by a break, usually.

$i=1;

switch($i){ //the variable is in brackets and the cases are in curly brackets

case 0:

print “zero”;

break;

case 1:

print “one”;

break;

default: //You can do a default case where the variable is something else!

print “whatever it is, it isn’t 0, 1 or 2”;

}

//result: one

The switch statement can deal with any simple type of data such as integers, floats and strings. This next example is the same as before in structure, except it uses strings:

$i=“tomatoes”;

switch ($i){

case “potatoes”:

print “spuds”;

break;

case “tomatoes”:

print “toms”;

break;

default:

print “Well, it could be anything!”;

}

//result: toms

Finally…


In this article we have covered the two types of Control Structures that PHP supports: Conditional Statements and Control Loops. These Structures are at the core of controlling program flow; the concepts introduced here will be used extensively from now on.

Next time, we will take take a look at pre-defined and user defined functions, which also play an important roll in the logical development and execution of a script.

Things to Remember:

  • Control Structures are at the core of programming flow, allowing you to branch the execution of scripts based on input and easily handle repeatitive tasks.
  • There are two types of Control Structures in PHP: Conditional Statements and Control Loops.
  • Conditional Statements and Loops having only one nested statement do not require brackets, however programmers frequently use them to make code more understandable. Nested statements are often indented for the same reason.
  • Break; can be used to end the execution of the current case. It can also be used to break out of for loops and while loops. Exit; terminates the execution entire script, and may be used anywhere within the script.

Comments 6

  • I think other website proprietors should take this web site as an model, very clean and great user genial style and design, as well as the content. You are an expert in this topic!

  • It’s actually a nice and useful piece of information. I am glad that you shared this helpful info with us. Please keep us informed like this. Thanks for sharing.

  • Great beat ! I would like to apprentice even as you amend your web site, how could i subscribe for a weblog website? The account helped me a applicable deal. I were tiny bit familiar of this your broadcast offered shiny transparent idea

  • Google

    Below you’ll come across the link to some web pages that we assume it is best to visit.

  • I’d observe all kinds of ads about blogging on the Internet to earn money, but how to start of anybody that has actually made anything this way. I’d love to listen to from anyone who has..

  • Once I originally commented I clicked the -Notify me when new comments are added- checkbox and now every time a comment is added I get 4 emails with the identical comment. Is there any manner you may remove me from that service? Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *