9 minutes to read, 2.23K views since 2017.02.03

Control flow structures in php

Control Flow structures in php

PHP as any (almost) programming language supports a number of traditional constructs for controlling the flow of execution of a program.

Conditional statements, such as if/else and others, allow a program to execute different pieces of code, or none at all, depending on some condition. Loops, such as while and for, allows to execute some part of code many times in a row.

This helps to build any kind of algorithms you need. So, basically, control flow structures is the only thing you need to know to build own complex applications.

Lets start.

If, else

The if statement checks the truthfulness of an expression and, if the expression is true, evaluates a statement. An if statement looks like:

if (expression)  {
 // some  statement
}

In this situation expression (in the brackets after if ) could be the variable, or some complex boolean expression made of conjunction of boolean operators and/or. For example:


$needToEcho = true;

if ($needToEcho) {
   echo "Hello world";
}

in this example you'd get Hello world on your screen if you execute the code, because the expression $needToEcho is true.

Example of complex boolean expression:

You can build as complex expressions as you need, for example $needToEcho && ($todayIsFriday || $todayIsWednesday) which would be true only if the $needToEcho is true and one of the $todayIsFriday or $todayIsWednesday is true.

Lets refresh in our memory what boolean operators exists in php

Boolean operators

  • and,&& - true if both of the operands true. For example $a && $b

  • or, || - true if one of the operands are true. Example false || 5 - true because 5 is considered as true.

  • == - true if two opearands are equal (regardless variable type). For example '5' == 5, number 5 equal to string '5'

  • === - true if two operands are equal including a type. previous example would be false because, number is not equal to string

  • ! (not, negation of the expression). For example !$a - true if the $a is false.

  • != (not equal) - true if operands are not equal. Example 5 != 4 is true.

  • Attention! You cant use !=== as not equal, you should negate equality expression instead: !($a === $b).

Else

In addition for handling part of code if the expression true you can use else word to execute some code if the expression is false:

if ($showForm) {
  // echo form
} else {
  echo "Form is disabled!";
}

You can use nested if-else blocks to handle different situations, for example:

if ($showForm) {
  if ($showTitleInput) {
    echo "<input name='title'>";
  }
  // and so on
}

Elseif

if you have one nested statements in your else block you can rewrite the following code

if ($x < 0) {
  // do something
} else {
  if ($x == 5) {
    echo 'var x is 5';
  }
  if ($x == 6) {
    echo 'var x is 6';
  }
}

to the following one

if ($x < 0) {

} elseif ($x == 5) {
  // ..
} elseif ($x == 6) {

}

Attention!

Dont forget about the order of code execution - top to bottom. So if the upper condition is true, rest of the code would not be executed in code written with elseif, but would be executed in previous example. So using elseif is only good when you have only one nested block in your else block. If you have many if's its better to use switch operator which would be reviewed further in this article.

Have questions? Write into comments

for, foreach, while

Most of the tasks programmers do they do with the similar data. For example you write the restaurant website. There is a menu with dishes, each dish have his price, title, weight, ingridients and so on.

Lets imagine you need to print the menu on some page in list view. It means you need to print each dish his price, description ...

Cycles would help you.

For

Most usable cycle is for, or how its called cycle with counter in other words. You say how many times to execute the code, introduce counter variable and say what to do with counter on each iteration (repeatable execution of cycled code). Lets get closer by next example:

for ($i = 0; $i <100; $i++) {
  echo $i . "</br>";
}

this code would print all numbers from 0 to 99. Why?

For cycle declaration has three parts, divided by ; (semicolon) :

  • Counter declaration$i = 0 - $i is a counter with start value 0
  • Exit condition $i < 100 - until this expression is true, code in square brackets would be executed.
  • Counter step $i++ - increment $i value after each iteration. So the $i variable each time has a new value. That's why we had such result in te end: a list of increasing numbers.

Atention

In this example we intentionally used $i variable as counter. You're allowed to use any variable name as a counter, but most used name is i - from iteration.

Also, we used here post increment ($i++) as a counter step. You're allowed to use any operation here. Take into account that if you make such situation when cycle newer stops it woudn't be an error, so program would hang executing infinity loop.

You can stop the cycle before the exit condition by break; word:

for ($i = 0; $i < 10000; $i++) {
  if ($i == 50) {
    break; // this will break the cycle loop
  }
}

also, if you need to skip some part of the code in the loop but don't break it you can use continue statement:

for ($i=0; $i < 1000; $i++){
  if ($i == 0) {
    continue; // function SomeBigFunction would not be called at this iteration
  }
  // this takes a lot of time
  someBigFunction();
}

Foreach

for cycle is good but foreach is better. In some cases.

For example you have an array of dishes $dishes. You need to iterate each of them. With for cycle:

$elements = count($dishes);
for ($i=0; $i < $elements; $i++) {

  // do some with $dish - its a current element
  $dish = $dishes[$i];
} 

We need to get a number of elements by counting an array before we start a cycle. Also we need to get an element by the index in the code: $dishes[$id]. It's not a problem actually, but still.

And here is the foreach example:

foreach ($dishes as $dish) {
  // here $dish is already a current element in $dishes array (analog of $dishes[$i]) above
}

It takes each element of a first variable and introduce it like second variable: $dishes[$i] as $dish.

Yeah, laconically. It's what called syntactic sugar - a shorter workaround for a programmer to do things which are able to reach by another (longer) ways.

While

while is the most general cycle. it can be used instead both for and foreach. Its very simple, accepts only one parameter - exit condition:

// this cycle works infinitely until some new messages for user found
while (true) {
  sleep(1000);
  $newMessagesForUser = getNewMessages();
  if(!empty($newMessagesForUser)){
    echo $newMessagesForUser;
    break;
  }
}

until condition is false, the cycle block would be executed. while is frequently used to generate infinitely loops. With brak; statements he creates powerfull instrument to make some great algorithms. In the example above it used to simulate real time messaging, which called long pulling and was very popular some time ago.

Also, while cycle can be used for tasks which generally handled with for:

while ($x < 5){
  echo $x;
  $x++;
}

the only difference is that you required to handle the step and counter itself by yourself.

Read next article Working with arrays in php5 in course Basic PHP