PHP Questions Home

Categories

Arrays
Files
Forms
Functions
Images
MySQL
Numbers
Others
Strings
Website


PHP Functions

PHP Functions


More PHP

Top Questions
Ask a Question

How can I add branching logic to my PHP code?


By logic we mean if / else code, for instance if it is raining then take an umbrella, else don't.

This is achieved with the if and else statements in PHP, and it is quite simple to do.

Here is an example of this in action, where you will get a different message depending on whether it is raining or not.

<?php
$itisraining 
1//yes it is raining

if ($itisraining) { echo "It is raining, take an umbrella"; }
else { echo 
"No need for an umbrella-ella today!"; }
?>


Points to note: the curly braces { } enclose each section of logic, e.g. an if or an else code. These are not strictly mandatory and you'll often see them dropped for short pieces of logic on one line but it is best to use them for clarity and to stop confusion.

Run this program twice and the second time set the variable at the top to '0'. You will notice that the 'if' statement evaluates '0' to false, whereas '1' is true.



More other PHP Questions

How do I add comments to my PHP script?
What is a constant in PHP?
What is the difference between the while and do while loops?
I have lots of if else logic - is there another option?
How do I find the timestamp for a particular date?