Ternary Operator - PHP - P27
The ternary operator is a way to quickly express if/else statements. The ternary operator follows the following syntax:
( boolean expression ) ? if_true : if_false;
If the boolean expression evaluates to true, the “if_true” result is displayed, otherwise the “if_false” result is displayed.
Just as a quick recap, the normal if/else syntax looks like the following:
$expression = true;
if ( $expression ) {
// do statement if true
} else {
// do statement if false
}
This gets redundant especially when you’re just echoing statements. You will need to write 2 different echo statements: one for the if true portion and the other for the if false portion. The ternary operator can be squeezed into a single echo statement itself.
echo ( boolean expression ) ? if_true : if_false;
Let’s look at an example.
$money = 2000;
echo ( $money == 2000 ) ? "Time to spend" : "Need more money";
Since the variable $money contains 2000, the expression $money ≥ 2000 evaluates to true, so “Time to spend” is displayed on the screen. If the value that was stored inside of the $money variable was less than 2000, you would see “Need more money” on your screen.
Ternary operators are also great when you need to assign values to a variable after some decision is made.
$money = 2000;
$isBuyingAMountainBike = ( $money == 2000 ) ? true : false;
In the statement above, PHP:
- Assigns 2000 to the $money variable.
- Progresses to the $isBuyingAMountainBike variable. It sees that it contains a ternary operator.
- PHP evaluates the expression, $money == 2000. The expression returns true.
- Since the expression returned true, PHP goes into the “if_true” portion of the ternary expression and sees that it contains the value true.
- The value true is assigned to the $isBuyingAMountainBike variable.
We could have easily placed Yes/No or 1/0 values instead of true/false for the ternary expression above.
The ternary operator should not be abused; it should only be used in simple if/else decision making. It you have nested expressions, you should try to either convert the nested boolean expression into a single expression with the help of logical operators, like the && operator, or simply use the if/else structure.
Read the full article on my website
https://www.dinocajic.com/php-ternary-operator/
Code for this tutorial
https://github.com/dinocajic/php-7-youtube-tutorials/blob/master/27%20Ternary%20Operator.php
Full Code
https://github.com/dinocajic/php-7-youtube-tutorials
PHP Playlist
https://www.youtube.com/playlist?list=PLbhJy0VhR6SAmoneYvF6Y_axQJKg7i50M
--
Dino Cajic
Author and Head of IT
Homepage: https://www.dinocajic.com
GitHub: https://github.com/dinocajic
Medium: https://medium.com/@dinocajic
Instagram: https://www.instagram.com/think.dino
LinkedIn: https://www.linkedin.com/in/dinocajic/
Twitter: https://twitter.com/dino_cajic
My Books
An Illustrative Introduction to Algorithms
https://www.amazon.com/dp/1686863268
Laravel Excel: Using Laravel to Import Data
https://amzn.to/4925ylw
Code Along With Me - PHP: From Basic to Advanced PHP Techniques
https://amzn.to/3M6tlGN
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Ternary Operator - PHP - P27», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.