Conditions and Branching

End to Linear Programs! The most basic principle of any program is "what happens if ...". The condition can be written as a logical statement that can be valid (the condition is met) or not valid (then it is not executed or its exact opposite is performed). Both are easy to define.

General notation

Generally, a condition can be written as a logical statement. The condition may be met or not. It is good to count both variants as possible. If there are multiple alternatives, this is called a nested condition.

Example:

if (operation value ) {
	// This is triggered if the condition is true 
} else { 
	// This is triggered if the condition does not apply
} 

We do not always have to define both variants (sometimes it is completely unnecessary). We can define the situation if only the condition applies. This is done as follows:

if (operation value) {
	// This is triggered if the condition is true 
}

Logical operators

Operator Meaning
== Equals
=== Equals and has the same data type (anything can be compared to anything, but the condition is met only if it is a value of the same data type (for example number, text,))
!= Does not equal
<= Equals or is greater
>= Equals or less
< Greater
> Less

Real demo

$a = 5; 
$b = 3; 
if ($a === $b) { 
	// block to be printed if $a equals $b
} else { 
	// block to be printed if $a is NOT equal to $b 
} 

Nested conditions

Unfortunately, the output is only true and false. So if we want to consider more options, we have to put more conditions into each other. This is called a nested condition. It is nested because one condition solution is another condition.

$a = 5;         // left pocket 
$b = 3;         // right pocket 
$pocket = true;  // do I have a pocket? 
 
if ($pocket === true) { 
 
	if ($a > $b) { 
		echo 'There's more in the left pocket'; 
	} else { 
		echo 'There is more in the right pocket'; 
	} 
 
} else { 
	echo 'You have no pocket'; 
} 

Previous chapter (Include (folding pages from pieces))

Back to Learn PHP main menu