当前位置:网站首页>PHP三元(三目)运算符
PHP三元(三目)运算符
2022-07-31 22:14:00 【小苗吃不够】
PHP三元(三目)运算符
语法格式:
(expr1) ? (expr2) : (expr3)
当expr1为true时(成立),返回值为expr2,当expr1为false时(不成立),返回值为expr3。
不理解继续向下看:
//三元运算符写法:
$a = 1;
echo !empty($a) ? $a : 'null'; //!empty($a)是true输出$a ,false输出'null'
//if写法:
$a = 1;
if(!empty($a)){
echo $a;
}else{
echo 'null';
}
上面两个表达式是一致的。
从PHP 5.3 起,可以省略三元运算符中间那部分。表达式 expr1 ?: expr3 ,当expr1为true时(成立)返回 expr1,否则返回 expr3。
//三元运算符写法:
$a = 1;
echo $a ?: 'null'; //$a是true输出$a , false输出'null'
//if写法
$a = 1;
if(!empty($a)){
echo $a;
}else{
echo 'null';
}
输出结果都是一样的,只不过三元运算符看上去更加简洁;
边栏推荐
猜你喜欢
随机推荐
BM5 合并k个已排序的链表
#yyds干货盘点# 面试必刷TOP101:链表中环的入口结点
Shell script quick start to actual combat -02
JS basic exercises
Verilog implements a divide-by-9 with a duty cycle of 5/18
基于STM32 环形队列来实现串口接收数据
A high-quality WordPress download site template theme developed abroad
Efficient Concurrency: A Detailed Explanation of Synchornized's Lock Optimization
renderjs usage in uni-app
One thing to say, is outsourcing company worth it?
Book of the Month (202207): The Definitive Guide to Swift Programming
Douyin fetches video list based on keywords API
A shortcut to search for specific character content in idea
架构实战营模块 8 作业
GateWay implements load balancing
Getting Started with Tkinter
Student management system on the first day: complete login PyQt5 + MySQL5.8 exit the operation logic
MATLAB program design and application 2.4 Common internal functions of MATLAB
Structure of the actual combat battalion module eight operations
The old music player WinAmp released version 5.9 RC1: migrated to VS 2019, completely rebuilt, compatible with Win11