The Ternary Operator in PHP

If you have a small if/else statement, it could possibly be turned into a ternary operator.

What is a ternary operator

The ternary operator is a comparison operator and can be looked at as basically a short-handed if/else statement. In my view, it’s great to use if you have a basic if/else statement and can reduce some code duplication. Plus it can be a lot nicer to read once you’re used to it.

Example — Anatomy of the Ternary Operator

Let’s say I want to check for some value:

$project = null; // let's say this value doesn't exist.
$project == null ? false : true; // returns false

As you can see from the expression above, $project == null ? false is our “if” statement and the logic following the colon “:” is our if statement. Altogether this is saying that if a project does not exist, then return false. Otherwise, return true.

Example from a project that I’m working on.

I’ve been working on a project management app, which I’m using Laravel for (a full-stack PHP web framework). In my project controller, I have a store method that stores the project in the database (yay, for following CRUD/REST patterns).

I didn’t want the deadline field to be required, but if it was left empty, I wanted to store a default deadline date and time. Something like thirty days from project creation.

Here was my original solution:

   /** 
    * Store project. 
    *
    * @todo Only users with project manager role can store projects.
    * @param Request $request
    * @return \Illuminate\Http\Response
    */
   public function store(Request $request)
   { 
     $this->validate($request, [
        'name' => 'required',
      ]);

    $project = new Project;
    $project->name = $request->input('name');
    if ($request->input('deadline') == null) {
        $project->deadline = Carbon::now()->addDays(30);
    }
    $project->deadline = $request->input('deadline');

    $project->save();

    return redirect('/')->with('success', 'Project created successfully!');     

   }

This totally works and is fine, but this is not ideal at all. C’mon Tyler! What were you thinking? One red flag and code smell is code duplication. http://firepowerrecords.com/releases/diamonds/ $project->deadline is repeated twice and we want to follow the DRY standard.

So the ternary operator to the rescue! Here is my updated solution:

/** 
 * Store project. 
 *
 * @todo Only users with project manager role can store projects.
 * @param Request $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{ 
    $this->validate($request, [
        'name' => 'required',
    ]);

    $default_deadline = Carbon::now()->addDays(30);

    $project = new Project;
    $project->name = $request->input('name');
    // if deadline request is empty, then store default deadline.
    $project->deadline = $request->input('deadline') == null ? $default_deadline : $request->input('deadline');

    $project->save();

    return redirect('/')->with('success', 'Project created successfully!');        
}

Ah, much nicer! I’m storing the default deadline in a Grottaglie $default_deadline variable which is storing the date using carbon. Then, I’m using the ternary logic within $project->deadline. If the project input field returns nothing then the default date is stored. Otherwise, the date from the input is stored. Perfect! This reduced code duplication and this looks much nicer. This also saved a coupe of lines of code.

Here’s a nice, fancy image of my code: Ternary Operator PHP

Closing Points

I hope this helps explain the ternary operator in PHP and where you can apply it. It can be helpful for small if/else logic and help clean up your codebase. Though, I should note that you shouldn’t use the ternary operator for large, complicated logic. That could get messy!

If you like to make a suggestion to improve this post, please leave a comment below. 🙂 Cheers and happy coding!

Tyler Souza

Tyler is a very passionate full-stack developer who thrives on a challenge. He specializes in programming (mainly in Python), REST API development, and keeps up with the latest front-end technologies. When not coding, he loves to eat ramen, BBQ, and travel.

You may also like...