PHP: Shortened If, Else Statements

How to use short-hand if statements to perform conditional execution of code.

2308 views
d

By. Jacob

Edited: 2019-12-15 18:48

short-hand if statements, PHP

There is a few ways to write shortened if statement in PHP.

Some short-hand ways of writing if else blocks are more readable than others, and some developers therefor prefer to stick with the more readable ones.

A basic statement either returning true or false can be written like this:

$consent_given = ($_COOKIE['consent'] == 'given') ? true : false;

If statements without Curly brackets:

if ($his_name == $my_name)
  echo "Hay! We got the same name!";

This example only works for a single expression, and has the disadvantage that the meaning is a bit more ambiguous. Personally, I avoid using this.

Ternary conditional operator:

$logged_in = true;
$guest = 'Viewing as Guest';
$user = 'Welcome back';

$welcome_message = $logged_in ? $user : $guest;

echo $welcome_message;

This uses the ternary operator to check if a user is logged in, and show an appropriate welcome message to the user.

Short conditional function call

$is_logged_in = false;

if (!$is_logged_in) user_role();

function user_role() {
  echo '<h1>You need to be logged in to view this page</h1>';
  exit();
}

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials