A ternary operator is a concise way to perform conditional logic within a single line of code. It is often used as a shorthand for simple if-else statements. The ternary operator is found in many programming languages, including C, PHP, C++, Java, Python, JavaScript, and as well as others. Using it instead of traditional conditional statements will reduce the amount of code on a file and therefor make the file size smaller. When using the expression in PHP and JavaScript, the syntax is as follows:
(Condition) ? Statement 1: Statement 2;
Condition is what is being evaluated. Statement 1 is if the condition is true. Statement 2 would trigger if the statement is false. It’s a shortcut for an if else statement.
You would use it in replacement of something like this:
$x=10;
if($x>=10)
{
echo "Hello";
}
else
{
echo "Hi";
}
That entire chunk of code can be replaced with:
$x=10;
echo ($>=10) ? "Hello" : "Hi";
That is much shorter, isn’t it? From 9 lines of code down to 2 lines.
What is even better is that if we are using PHP, we can make it even shorter. Let’s say you have something like this:
$id= isset($_GET["id"]) ? $_GET["id"] : "0";
We can make that even shorter in PHP by doing the following:
$id= $_GET["id"] ?? "0";
There you have it, now you know multiple ways to tighten up your code and make the filesize smaller. Will you be rewriting some of your if statements to use ternary operators?