Home > php教程 > php手册 > body text

php中三元运算符用法详解

WBOY
Release: 2016-06-13 10:16:49
Original
1209 people have browsed it

三元运算符,是软件编程中的一个固定格式,即( ?: )(注:括号里面的内容才是正确的格式)。

语法:条件 ? 结果1 : 结果2

说明:问号前面的位置是判断的条件,如果满足条件时结果1,不满足时结果2。

 

 代码如下 复制代码

$id = isset($_GET['id']) ? $_GET['id'] : false;

?>

一条代码替代了很多的代码。首先,它使用isset ()函数,检查$_GET['id']是否存在。如果$_GET['id']确实存在,它将返回它的价值。但是,如果它不存在,条件即为假,这时返回的是false。$id的值取决于$_GET['id']是否存在。所以,基本上,如果$_GET['id']存在,$id=$_GET['id'],反之$id=false。


用“?:”条件语句检验用户输入值:

 代码如下 复制代码

$filename = isset($argv[1]) ? $argv[1] : "php://stdin";
$fp = @fopen($filename, ‘r’) or die("Can’t Open $filename for reading");

while (!@feof($fp)) {
    $line = @fgets($fp, 1024);
    print $line;
}

@fclose($fp);
?>

前面使用三元运算符的代码和下面的代码等同:

 代码如下 复制代码

if (isset($argv[1])) {
    $filename = $argv[1];
} else {
    $filename = "php://stdin";
}
?>

可以看出,假设用普通的if-else结构写上述代码,代码量会比上面多出许多,但第二种形式更易理解,而且不要求更多的录入。所以在挑选三元运算符时,请务必权衡一下利弊。

三元运算符优点

PHP中的三元运算符(?:)大大减少了程序员写这些语句的时间。它的语法如下:

condition ? do_if_true : do_if_false;

三元运算符不是一种必不可少的结构,但却是一种美化代码的途径。同样,它可以取代不好的if…else代码块,并且可以提高代码的可读性。

同样,用户可以使用PHP的or运算服赋予变量默认值:

 代码如下 复制代码

$filename = $argv[1] or $filename = "php://stdin";
?>

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!