Flow control statement in php

2.5.3. while

The simplest form of loop is the while statement:

while (expression) 
  statement

If the expression evaluates to true, the statement is executed and then the expression is reevaluated (if it is true, the body of the loop is executed, and so on). The loop exits when the expression evaluates to false.

As an example, here's some code that adds the whole numbers from 1 to 10:

$total = 0;
$i = 1;
while ($i <= 10) {
  $total += $i;
}

The alternative syntax for while has this structure:

while (expr): 
  statement; 
  ...; 
endwhile;

For example:

$total = 0;
$i = 1;
while ($i <= 10):
  $total += $i;
endwhile;

You can prematurely exit a loop with the break keyword. In the following code, $i never reaches a value of 6, because the loop is stopped once it reaches 5:

$total = 0;
$i = 1;
while ($i <= 10) {
  if ($i == 5)
    break; // breaks out of the loop
  $total += $i;
  $i++;
}

Optionally, you can put a number after the break keyword, indicating how many levels of loop structures to break out of. In this way, a statement buried deep in nested loops can break out of the outermost loop. For example:

$i = 0;
while ($i < 10) {
  while ($j < 10) {
    if ($j == 5)
      break 2; // breaks out of two while loops
    $j++;
  }
  $i++;
}
echo $i; 
echo $j; 
0
5

The continue statement skips ahead to the next test of the loop condition. As with the break keyword, you can continue through an optional number of levels of loop structure:

while ($i < 10) {
  while ($j < 10) {
    if ($j = 5)
      continue 2; // continues through two levels
    $j++;
  }
  $i++;
}

In this code, $j never has a value above 5, but $i goes through all values from 0 through 9.

PHP also supports a do /while loop, which takes the following form:

do 
  statement
while (expression)

Use a do/while loop to ensure that the loop body is executed at least once:

$total = 0;
$i = 1;
do {
  $total += $i++;
} while ($i <= 10);

You can use break and continue statements in a do/while statement just as in a normal while statement.

The do/while statement is sometimes used to break out of a block of code when an error condition occurs. For example:

do {
  // do some stuff
  if ($error_condition)
    break;
  // do some other stuff
} while (false);

Because the condition for the loop is false, the loop is executed only once, regardless of what happens inside the loop. However, if an error occurs, the code after the break is not evaluated.

Flow control statement in php

It’s time to get with the program friends – we need to Go With The Flow. In this episode of our PHP Tutorial Series we’ll be taking a closer look at all of the Flow Control Statements available to us. When we’re working with these control statements, we’ll be evaluating variables and expressions for a boolean value and then taking action based on a true or false state. Aren’t you so glad we just covered booleans now?! In any event we have a lot to cover, we’ll look at if, elseif, ternary, switch, while, for, foreach, try catch, and return. Let’s jump into working with the various flow control statements we have in PHP!


1. if

The workhorse of creating basic conditional logic in your programs is the trusty if statement. We use the if statement to check the boolean value of a variable or expression contained within a pair of parenthesis. The expression is checked, and if it is true, the statement will run. No doubt you have seen this before, but let’s look at the structure of this statement here.

if(expression) {
    statement
}

Just as useful is the ability to specify some other statement to run should the expression being evaluated be false. We can do that with this structure.

if(expression) {
    statement
} else {
    statement
}

There are opinions abound on the use of the curly braces. If you were to omit them, the code would still run. There is a fair chance however that the code readability police will hunt you down and place you under arrest for sloppy coding. The take away, use your curly braces! If you really have a thing against the curly braces, you could use this alternative syntax as well.

if(expression) :
    statement
  else :
    statement
endif;

This approach sometimes works if there are large amounts of html in the file you happen to be working with. You might see this type of syntax in a view file for instance in a model view controller type application. You can also nest if statements to get the behavior you want.

if (expression) {
    statement
} else {
    if (expression) {
        statement
    } else {
        statement
    }
} 

You can use the above style all you like. If you want to use yet another syntax for the same effect, you can do that as well. This would be by combining the else and if into one elseif. This approach is not mandatory, in fact some would say the first approach is a bit more readable. We’ll show how to use this additional syntax however for completeness.

if (expression) {
    statement
} elseif (expression) {
    statement
} else {
    statement
}

As they say in Hollywood, whatever blows your hair back friend.


2. ? :

You may be wondering, whats up with the question mark colon in large font? This is the ever useful ternary operator, and you can think of it as a shorthand expression of a simply if statement. It’s a handy syntax that isn’t used as much as you’d think it would be. With the ternary operator, the expression is first evaluated. Then, if that expression is true, statement1 will run. If the expression is false, statement2 runs. The syntax is shorter, but contrary to the if statement, it is sometimes not clear exactly what the intended effect was meant to be when reading the code at a later time. This is the syntax if you would like to use it.

(expression) ? statement1 : statement2


3. switch

Now we move on to the switch statement. When would we want to use the switch statement? The switch statement is good when a variable could have one of several values, and each value would have a different operation associated with it. A good example might be a variable of $day. Consider there are seven days in the week, and depending on the day of the week, your program would take a different action for each scenario. This is how the syntax looks.


switch ($day) {
    case 'Monday':
        // wipe the cobwebs from your eyes
        break;
    case 'Tuesday':
        // do productive stuff at work
        break;
    case 'Wednesday':
        // cheer for hump day
        break;
    case 'Thursday':
        // grab a beverage on thirsty Thursday
        break;
    case 'Friday':
        // Celebrate the Weekend
        break;
    case: 'Saturday':
        // Keep Celebrating 
        break;
    case: 'Sunday':
        // go to Church
    default:
        // Have a default action if the $day is something other than
        // Monday - Sunday
        break;
}

There might be a scenario where you want the same action to take place for several different states of the variable being tested. Maybe you’d like to start celebrating the weekend on Wednesday, Thursday, and Friday. You can do just that with a fall through like this.


switch ($day) {
    case 'Monday':
        // wipe the cobwebs from your eyes
        break;
    case 'Tuesday':
        // do productive stuff at work
        break;
    case 'Wednesday':
    case 'Thursday':
    case 'Friday':
        // Celebrate the Weekend
        break;
    case: 'Saturday':
        // Keep Celebrating 
        break;
    case: 'Sunday':
        // go to Church
    default:
        // Have a default action if the $day is something other than
        // Monday - Sunday
        break;
}

4. while

Moving on in our control flow adventures brings us to the while loop. This is the first loop we have taken a look at. The format follows this format.

while(expression) {
    statement
}

That looks an awful lot like an if statement you might be thinking. In fact you are right, the only difference is that the if is now a while. The way this works is expression is evaluated and if it is true, the statement runs. The expression then gets evaluated again, and if still true, the statement runs again. This happens at lightning quick speed, and you can complete hundreds of statement executions very quickly. The statement will usually have an ability increment the expression so that the loop does not run forever. If it did not have this ability, the loop might continue to infinity and the world would end program would crash. Let’s count by tens to 100 with a while loop.

<?php

$i = 1;
while($i <= 10) {
    echo ($i * 10);
    echo '<br>';
    $i++;
}

?>

10
20
30
40
50
60
70
80
90
100

Easy Peasy Lemon Squeesy, People. One other thing you might like to do with your loops is to be able to filter within them and break out of them if needed. You can do this by placing an if inside the loop and a break inside the loop respectively. Let’s check each number to see if it is evenly divisible by 3 and output a message indicating so if this is the case. Let’s also break out of the loop at 80.

<?php

$i = 1;
while($i <= 10) {
    
    $num = ($i * 10);
    
    if(is_int($num / 3)) {
        
        echo "$num is divisible by 3";
        
    } else {
        
        echo "$num is not divisible by 3";
    }
    
    echo '<br>';
    $i++;
    
    if($num == 80){
        break;
    }
}

?>

10 is not divisible by 3
20 is not divisible by 3
30 is divisible by 3
40 is not divisible by 3
50 is not divisible by 3
60 is divisible by 3
70 is not divisible by 3
80 is not divisible by 3

Smashing! That was awesome stuff.


5. do while

You could rewrite the prior example with a do while loop. The difference with a do while loop is that since the while condition comes after the actual statement code, the loop will always run at least a minimum of one time no matter what. With the standard while loop, there is a chance that the loop will never run at all, since if the expression is false, the loop won’t run! You’ll have to explore your use case, but it’s safe to say that do while loops are far less common than while and the other types of loops. This is how to write one if you like though.

<?php

$i = 1;
do {
    
    $num = ($i * 10);
    
    if(is_int($num / 3)) {
        
        echo "$num is divisible by 3";
        
    } else {
        
        echo "$num is not divisible by 3";
    }
    
    echo '<br>';
    $i++;
    
    if($num == 80){
        break;
    }
} while($i <= 10);

?>

6. for

The for loop is really the workhorse of looping constructs. It’s a little more clean than the while loop since it builds the counter right into the expression. No need to have an iterator in the statement body of the loop with this scenario. We can rewrite our little counting program with a for loop just like this. Note that the filtering and break mechanisms work just as well in for loops as they did with while loops. In fact, let’s do the same program but count by 100’s this time and break the loop at 700. Observe.


<?php

for($i = 1; $i <= 10; $i++) {
    
    $num = ($i * 100);
    
    if(is_int($num / 3)) {
        
        echo "$num is divisible by 3";
        
    } else {
        
        echo "$num is not divisible by 3";
    }
    
    echo '<br>';
    
    if($num == 700){
        break;
    }
} 

?>

100 is not divisible by 3
200 is not divisible by 3
300 is divisible by 3
400 is not divisible by 3
500 is not divisible by 3
600 is divisible by 3
700 is not divisible by 3

Oh man, that is Cool and The Gang!


7. foreach

We talked a lot about arrays in this PHP Tutorial Series. We even came up with an Epic PHP Array Functions List to keep as a reference. The time has come now, for us to iterate over arrays. We will do this with the always useful foreach construct. Sometimes you’ll just want the values, and other times you might like to get the keys and the values. There are also a couple of ways to create the loop, so in total you have four options for the syntax.

foreach ( $array as $value ) {
    // do stuff to the value
}

foreach ( $array as $value ):
    // do stuff to the value
endforeach;


foreach ( $array as $key => $value ) {
    // do stuff to the key and value
}

foreach ( $array as $key => $value ):
    // do stuff to the key and value
endforeach;

Now let’s put our foreach skills into action. Let’s say we have an array of stocks and we want to process each one of them in turn. We’ll take an array of ticker symbols that are in all lowercase. We’ll then place a function inside the loop of our foreach construct, and each time the loop runs, and new lowercase ticker symbol will be fed into our strtoupper function. We’ll simply echo this process out to the browser to see it in action.

<?php

$stocks = array('msft', 'goog', 'aapl', 'adbe', 'csco', 'jnpr', 'gpro', 'nflx');

foreach($stocks as $stock) {
    echo strtoupper($stock).'<br>';
}

?>

MSFT
GOOG
AAPL
ADBE
CSCO
JNPR
GPRO
NFLX

Now we want to be able to process not only the ticker symbol, but the name of the company each ticker symbol is associated with. We can do this using the key value pair syntax of our foreach loop. Check it out.

<?php

$stocks = array(
    'msft' => 'Microsoft',
    'goog' => 'Google',
    'aapl' => 'Apple',
    'adbe' => 'Adobe',
    'csco' => 'Cisco',
    'jnpr' => 'Juniper',
    'gpro' => 'Go Pro',
    'nflx' => 'Netflix'
);

foreach ($stocks as $stock => $company) {
    echo 'The stock ticker for ' . $company . ' is ' . strtoupper($stock) . '<br>';
}

?> 

The stock ticker for Microsoft is MSFT
The stock ticker for Google is GOOG
The stock ticker for Apple is AAPL
The stock ticker for Adobe is ADBE
The stock ticker for Cisco is CSCO
The stock ticker for Juniper is JNPR
The stock ticker for Go Pro is GPRO
The stock ticker for Netflix is NFLX

So you can see that by using the foreach construct we can quickly get access to indices, keys, and values in both standard index based arrays as well as associative arrays.


8. try catch

We all know that computers and the software that run them are 100% fail proof, error free, and work perfectly at all times. If you believe that last sentence, there is a bridge in Brooklyn you may consider buying 🙂 Actually, the try catch construct is available to us for the very fact that sometimes things can and will go wrong with our software. The try catch gives us the ability to try something out, and if things don’t go as planned we have a contingency plan to handle any problems. A perfect example is connecting to a database. There are several things that could go wrong. To deal with this, just put your code in a try catch block like so.

<?php

try {
    $dbhandle = new PDO('mysql:host=localhost; dbname=vegibit', 'root', '');
    if ($dbhandle) {
        echo 'We are ready to work with the database!';
    }
    
}

catch (PDOException $error) {
    echo "Whoops! That was an error:  " . $error->getMessage() . "<br/>";
    die();
}

?> 

We are ready to work with the database!

If something went wrong, like the database not being found, we get an error.

<?php

try {
    $dbhandle = new PDO('mysql:host=localhost; dbname=verge', 'root', '');
    if ($dbhandle) {
        echo 'We are ready to work with the database!';
    }
    
}

catch (PDOException $error) {
    echo "Whoops! That was an error:  " . $error->getMessage() . "<br/>";
    die();
}

?> 

Whoops! That was an error: SQLSTATE[HY000] [1049] Unknown database ‘verge’

Script ended unexpectedly.


9. return

The return statement is used so much we don’t even think of it many times. It just exists happily in our code, returning values or control to the calling code going about it’s business. Usually we’ll see a return control statement being used in a function something like this.

<?php

function add ($num1, $num2) {
    return $num1 + $num2;
}

$result = add(5,7);

echo $result;

?> 

12

In this code we create a user defined function that returns a value. You can see when we call that function by simply writing it’s name and passing in two variables, it assigns or returns the sum into the variable $result. We are then free to echo out that value to the screen. Pretty Slick!

What is flow control statement?

Within an imperative programming language, a control flow statement is a statement that results in a choice being made as to which of two or more paths to follow.

What are the 3 types of control structures in PHP?

PHP supports a number of different control structures:.
elseif..
switch..
while..
do-while..
foreach..

What are the three control flow statements?

For controlling the flow of a program, the Java programming language has three loop constructs, a flexible if - else statement, a switch statement, exception-handling statements, and branching statements.

How many control statements are there in PHP?

There are two basic types of the first kind of Control Statement in PHP(conditional statements) in any programming language, IF, ELSE, and ELSEIF Statements. SWITCH Statement.