Share via:

PHP: If, Else Statements

How to create a simple If- Else Statement in PHP to perform conditional execution of code.

129 views

Edited: 2019-12-17 18:15

If else, PHP

This tutorial discusses how to write a simple if, else statement in PHP.

We can either choose to use the "more readable" form, complete with parentheses and curly brackets, or we can use a shorter version. In this tutorial I will show you how to do both. Which one is the better one to use will depend mostly on the circumstances.

If statements is a concept that is shared across programming languages. So, if you know how to use them in one language, it will generally be much easier for you to use them in another.

An if statement looks like this:

if ($some_variable == $another_variable) {
  echo 'The variables matched!';
} else {
  echo 'The variables did not match';
}

Or, using Colon and semi-colon

if (100 == $age):
  echo 'You have reached one hundred years of age.';
else:
  echo 'Still not there yet...';
endif;

Arrays instead of if, else

In a great deal of cases, you can actually just "select" the data you need to use, rather than first use conditional statements. This can both make your code more easy on the eyes to look at, and increase the performance of your application.

If you can reliably predict the content of a variable, then you might use it directly in an array to select the element of interest:

$user_roles_arr = array(
  'admin' => array('edit', 'create', 'delete', 'deactivate', 'comment', 'view'),
  'user' => array('edit_own', 'create', 'delete_own', 'deactivate_own', 'comment', 'view'),
  'guest' => array('view')
);

Now, to select the relevant user roles we simply do like this:

$user_role = 'admin';

print_r($user_roles_arr["$user_role"]);

Instead of hard-coding the user roles, we can easily modify the above to load the roles from a database. However, for many smaller applications, hard-coding user roles is fine, as it avoids overengineering the solution.

Comments