在PHP中调用if/else语法的替代方法是什么? [英] What is this alternative if/else syntax in PHP called?

查看:466
本文介绍了在PHP中调用if/else语法的替代方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下类型的if/else语法的名称是什么:

print $foo = ($hour < 12) ? "Good morning!" : "Good afternoon!";

我在php手册中找不到任何专用页面.我知道它的存在,因为我已经读过一本书(去年),现在我发现了这本书解决方案

这称为三元表达式

http://php.net/manual/en/language.expressions.php

您应该注意,这不是"if的替代语法",因为它不应用于控制程序的流程.

在设置变量的简单示例中,它可以帮助您避免冗长的if语句,例如:(ref:

What is the name of the following type of if/else syntax:

print $foo = ($hour < 12) ? "Good morning!" : "Good afternoon!";

I couldn't find any dedicated page in the php manual. I knew that it existed, because I've read a book (last year) with it, and now I found this post.

解决方案

This is called a ternary expression

http://php.net/manual/en/language.expressions.php

You should note, this is not an "alternate syntax for if" as it should not be used to control the flow of a program.

In the simple example of setting variables, it can help you avoid lengthy if statements like this: (ref: php docs)

// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

However it can be used other places than just simple variable assignent

function say($a, $b) {
    echo "{$a} {$b}";
}

$foo = false;

say('hello', $foo ? 'world' : 'planet');

//=> hello planet

这篇关于在PHP中调用if/else语法的替代方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆