How to write ternary expression in php

青灯夜游
Release: 2023-03-14 22:52:01
Original
4499 people have browsed it

In PHP, ternary expressions can implement simple conditional judgment functions. The writing method is "expression 1? expression 2: expression 3"; if the condition "expression 1" is established, the statement is executed "Expression 2", otherwise execute "Expression 3".

How to write ternary expression in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

Ternary operation in php

Ternary operation can implement a simple conditional judgment function, that is, based on the result of the first expression, select one of the other two expressions and execute

Ternary operation expression The way of writing:

表达式1?表达式2:表达式3
Copy after login

means: if the condition "Expression 1" is true, execute the statement "Expression 2", otherwise execute the "Expression 3"

The sample code is as follows:

<?php
    $a = 10;
    $a % 2 == 0 ? print &#39;$a 是偶数!&#39; : print &#39;$a 是奇数!&#39;;
?>
Copy after login

The running results are as follows:

$a 是偶数!
Copy after login

In addition, Expression 2 and Expression 3 can also use single quotes ('') or double quotes ("") to omit any one of them to avoid unnecessary code, as shown below:

<?php
    $a = 10;
    $b = 7;
    $a % 2 == 0 ? print &#39;$a 是偶数!<br>&#39; : "";
    $b % 2 == 0 ? &#39;&#39; : print &#39;$b 是奇数!&#39;;
?>
Copy after login

The running result is as follows:

$a 是偶数!
$b 是奇数!
Copy after login

Note: When using ternary arithmetic, if you need to print a string, it is recommended to use the print statement instead of the echo statement.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to write ternary expression in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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 admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template