Short Hand If
PHP allows you to simplify your code by writing single-line if
statements when conditions are straightforward.
Example
Here’s an example where we check the speed of a motorcycle. If its speed is less than 60, we assign a message to buy a Kawasaki:
$speed = 45; // Motorcycle's speed if ($speed < 60) $message = "Consider buying a Kawasaki."; echo $message;
Short Hand If…Else
You can also condense an if...else
statement into one line using the ternary operator. This method is concise and ideal for simple conditions.
Example
Let’s say we want to evaluate a car’s price. If the price is less than $20,000, it will recommend a Toyota; otherwise, it suggests a Mercedes:
$price = 25000; // Price of the car $message = $price < 20000 ? "Go for a Toyota." : "Try a Mercedes."; echo $message;