Ternary operator in PHP
The Ternary operator in PHP is a built-in operator that acts like an if statement in PHP. It shares with several other languages.
It has an unusual form, here it is:
Syntax: $result = condition ? expression1 : expression2;
Okay, what’s that…? What’s going on here? IF condition is true, the ternary operator—which is made up of characters ?:
—returns expression1. Otherwise, it returns expression2. So as we can see this is an operator that lets us make real-time choices. Let’s take an example. This code displays “its raining outside.” If the raining variable is true, and “I’m sleeping inside.” Otherwise:
<?php
$raining=TRUE;
if($raining==TRUE)
{
echo “Its raining outside.”;
}
else
{
echo “I’m sleeping inside.”;
}
?>
Here’s the same code using the ternary operator—note down how compact this is:
<?php
$raining=TRUE;
echo ($raining==TRUE) ? “its raining outside.” : “I’m sleeping inside.”;
?>
That’s it. Pretty cool huh!
If you have any issue, let us know in the comment box.
Latest
SOLID Principles: A Comprehensive Guide with Examples
Dec 22, 2024
React useEffect, useMemo, and useCallback: A Comprehensive Guide
Nov 23, 2024
React Component Structure, Composition, HOCs and Optimization with Examples
Oct 4, 2023
How to copy text to the clipboard in React.js
Sep 29, 2023
News
Pure html popover API is coming in Chromium 114
Sep 24, 2023
GitHub and OpenAI launch Copilot - an AI pair programmer
Jul 1, 2021
CSS aspect-ratio property
Jan 31, 2021
AWS UI - a collection of React components
Jan 20, 2021
Featured
SOLID Principles: A Comprehensive Guide with Examples
Dec 22, 2024
React useEffect, useMemo, and useCallback: A Comprehensive Guide
Nov 23, 2024
Axios Interceptors in a React application
May 27, 2023
Mastering Laravel: Exploring the Power of implode() and explode() Functions for String Manipulation
May 22, 2023