Shorthand if Statements and Adding Class Names in PHP

When you first start front-end development, tying together function to the HTML DOM elements can be difficult/confusing. One of the fundamental way to communicate to a user that something is active is by adding a class to a DIV or other elements within your HTML therefore activating additional styling.

In this tutorial we assume that you have an understand of what an iIf statement is and also that you understand what a foreach statement does within the context of PHP.

To do this, you can pull through information such as dates, tags, colors, or whatever other fields you have. But to output the data in the DOM using a straight php if statement can be messy at best.

So, this is why PHP shorthand exists! What is a PHP shorthand If statement? It is a short version of the full IF statement that you can directly “echo” out.

Let me show you by example two scenarios.


Example 1: Adding an Active Class

The example below uses the foreach key as a way to see if the post is the first post in a blog like scenario:

<?php foreach($posts as $k=>$post):?>   
    <div class=”test <?php echo $k ? ‘’ : ‘first’;?>”>Title and stuff</div> 
<?php endforeach;?>

In this above example, the line <?php echo $k ? ‘’ : ‘first’;?> uses the PHP IF shorthand.
What the hell does this mean? If the shorthand was to be written out as a normal PHP if statement, it would be like below:

if($k == false){
  echo ‘first’;

To explain the shorthand, let’s talk about the “foreach” iterator first. The foreach iterator sets the $k key value as 0 (also known to the if statement as “false”) on the first iteration. Thus, it detects the statement as true beyond the first iteration. (Keys start with zero, but accumulates on each iteration.) Also note that we’re assuming the $posts to be an iterable object.

The anatomy of a short hand if statement goes like this:

echo $variable_being_judged ? ‘do this if true’: ‘echo this if false’’



Foreach sets $k as zero the first time around. If something is false, so the second option (false option) gets picked from the shorthand if statement.


Example 2: Detecting words in a string

<?php foreach($posts as $post);?>
  <div class=”<?php echo strpos($post->name, ‘red’) !== false ? ‘red’ : ‘normal’ ?>”>
    <?php echo $post->name;?>
<?php endforeach;?>

What do you think this one does? Its pretty simple. This time, we’re seeing if the post name contains the word “red”. If it does contain the word red, then the class “red” is added to the div.

As an additional resource for if/else conditionals: PHP Shorthand If / Else Examples. Have fun with PHP and be safe, use a Framework!