If statements using colon and semi-colon style in PHP

How to use the alternative syntax of writing if statements in PHP to perform conditional execution of code.

2800 views
d

By. Jacob

Edited: 2021-02-14 03:09

Alternative syntax, PHP if statements.

In PHP, there is an alternative syntax for writing if statements when performing conditional execution of code, allowing us to use colon and semi-colon when writing the if statement.

This syntax is using endif keyword to finish the if statement.

A single if block will look like this:

if ('John' == $name):
  echo 'Hallo Rasmus :-)';
endif;

Including an else case in the statement:

if ('Zeev' == $name):
  echo 'Hallo Zeev :-)';
else:
  echo 'Sorry. I do not know you.';
endif;

Finally, we may also use the elseif keyword:

if ('Andi' == $name):
  echo 'Hallo Andi :-)';
elseif ('Rasmus' == $name):
  echo 'Hallo Rasmus!';
elseif ('Zeev' == $name):
  echo 'Hallo Zeev!';
endif;

Short-hand style

Of course, colons are also used as an else substitute in one-line if statements.

This is how to check if a variable is empty in a nice little one-liner:

// Assign a $_POST variable if it was not empty
$name = if (!empty($_POST['name'])) ? $_POST['name'] : null;

This is very readable and useful when you have a lot of user-input that you need to validate.

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