PHP Control Structures
if else
The if statement in the example above allows to execute a code fragment, when the condition is met. When you want to execute a code fragment, when the condition is not met you extend the if with an else.
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
The ternary operator as shorthand syntax for if-else
The ternary operator evaluates something based on a condition being true or not. It is a comparison operator and often used to express a simple if-else condition in a shorter form. It allows to quickly test a condition and often replaces a multi-line if statement, making your code more compact.
This is the example from above using a ternary expression and variable values:
$a=1; $b=2;
echo ($a > $b) ? "a is greater than b" : "a is NOT greater than b";
Output
while
while loop iterates through a block of code as long as a specified condition is true.
$i = 1;
while ($i < 10) {
echo $i;
$i++;
}
Output
do-while
do-while loop first executes a block of code once, in every case, then iterates through that block of code as long asa specified condition is true.
$i = 0;
do {
$i++;
echo $i;
} while ($i < 10);
Output
goto
The goto operator allows to jump to another section in the program. It's available since PHP 5.3.
The goto instruction is a goto followed by the desired target label: goto MyLabel;.
The target of the jump is specified by a label followed by a colon: MyLabel:.
This example will print Hello World!:
<?php
goto MyLabel;
echo 'This text will be skipped, because of the jump.';
MyLabel:
echo 'Hello World!';
?>
include & require
require
require is similar to include, except that it will produce a fatal E_COMPILE_ERROR level error on failure. When the require fails, it will halt the script. When the include fails, it will not halt the script and only emit E_WARNING.
require 'file.php';
include
The include statement includes and evaluates a file.
./variables.php
$a = 'Hello World!';
./main.php`
include 'variables.php';
echo $a;
Output
Be careful with this approach, since it is considered a code smell, because the included file is altering amount and content of the defined variables in the given scope.
You can also include file, which returns a value. This is extremely useful for handling configuration arrays:
configuration.php
<?php
return [
'dbname' => 'my db',
'user' => 'admin',
'pass' => 'password',
];
main.php
<?php
$config = include 'configuration.php';
This approach will prevent the included file from polluting your current scope with changed or added variables. include & require can also be used to assign values to a variable when returned something by file.
Example :
include1.php file :
<?php
$a = "This is to be returned";
return $a;
?>
index.php file :
$value = include 'include1.php';
for
for loops are typically used when you have a piece of code which you want to repeat a given number of times.
for ($i = 1; $i < 10; $i++) {
echo $i;
}
Output
foreach
foreach is a construct, which enables you to iterate over arrays and objects easily.
$array = [1, 2, 3];
foreach ($array as $value) {
echo $value;
}
Output
To use foreach loop with an object, it has to implement Iterator interface.
When you iterate over associative arrays:
$array = ['color'=>'red'];
foreach($array as $key => $value){
echo $key . ': ' . $value;
}
Output
switch
The switch structure performs the same function as a series of if statements, but can do the job in fewer lines of code. The value to be tested, as defined in the switch statement, is compared for equality with the values in each of the case statements until a match is found and the code in that block is executed. If no matching case statement is found, the code in the default block is executed, if it exists.
Each block of code in a case or default statement should end with the break statement. This stops the execution of the switch structure and continues code execution immediately afterwards. If the break statement is omitted, the next case statement's code is executed, even if there is no match. This can cause unexpected code execution if the break statement is forgotten, but can also be useful where multiple case statements need to share the same code.
switch ($colour) {
case "red":
echo "the colour is red";
break;
case "green":
case "blue":
echo "the colour is green or blue";
break;
case "yellow":
echo "the colour is yellow";
// note missing break, the next block will also be executed
case "black":
echo "the colour is black";
break;
default:
echo "the colour is something else";
break;
}
In addition to testing fixed values, the construct can also be coerced to test dynamic statements by providing a boolean value to the switch statement and any expression to the case statement. Keep in mind the first matching value is used, so the following code will output "more than 100":
$i = 1048;
switch (true) {
case ($i > 0):
echo "more than 0";
break;
case ($i > 100):
echo "more than 100";
break;
case ($i > 1000):
echo "more than 1000";
break;
}