New Horizons Get Schooled Blog

Shorten IF/ELSE constructions with ternary operators (PHP)

Shorten IF/ELSE constructions with ternary operators (PHP)Heavy code weighs the system down like a stick tied to a rock and thrown in a river. However, there is an opportunity to lighten code with ternary operators. IF/ELSE statements work great and are easy to code, but they usually end up too long and taxing. Fortunately, IF/ELSE statements aren’t always optimal or necessary, which is where the ternary operators step in.

Ternary operators use "(condition) ? (true return value) : (false return value)" statements to shorten IF/ELSE structures to a more manageable weight while retaining their original function. For example: $message = 'Greetings '.($user->get('first_name') ?: ‘Guest'); instead of $message = 'Greetings '.($user->is_logged_in() ? $user->get('first_name') : ‘Guest’);.

Posted on 10/30/18 8:00 AM by Get Schooled in PHP

Get Schooled

Written by Get Schooled

Search by Topic

    Lists by Topic

    see all

    Be at the center of it all.


    Knowledge Ninjas

    a web-based service that allows software application end users to access a subject matter expert in real-time via a chat interface to resolve questions or problems they encounter in their specific software.