PHP If Statements are the beginning of logical operators and are a very important part of programming. They allow you to create code that only runs if certain conditions are true. The basic format of an If Statement looks like this:
if (condition) { php statements }
Let’s create a basic example.
<?php if (2 > 1) { echo "True!"; } ?>
This works because 2 is in fact greater than 1. If we switch it around, we see that nothing happens:
<?php if (1 > 2) { echo "True!"; } ?>
PHP looks at this, checks the condition, sees that 1 is not greater than 2, and so ignores the echo statement.
Here’s a more practical example. Let’s say you’re using PHP’s date function to grab the month from the server and store it in the $month variable. Perhaps you want to give a special message to your visitors at certain times:
<?php if ($month == "December") { // If the $month equals December, proceed. echo "Happy Holidays!"; // Wish our visitors a happy holiday season! } ?>
If Statements are very powerful and they are used a lot. But what if you want something to happen by default if your If Statement condition is not met? Let’s take a look at that now with PHP Else and Elseif Statements.
Go back to Building PHP Scripts.
Tags: if, php, programming, statements, tutorial