삼항 연산자
삼항 연산자는 if else 문을 하나의 문으로 바꾸는 데 사용됩니다.
구문
(condition) ? expression1 : expression2;
동등식
if(condition) {
return expression1;
}
else {
return expression2;
} 조건이 true이면 expression1의 결과를 반환하고 그렇지 않으면 expression2의 결과를 반환합니다. void는 조건이나 표현식에서 허용되지 않습니다.
널 병합 연산자
Null 병합 연산자는 변수가 null인 경우 null이 아닌 값을 제공하는 데 사용됩니다.
구문
(variable) ?? expression;
동등식
if(isset(variable)) {
return variable;
}
else {
return expression;
} 변수가 null이면 표현식의 결과를 반환합니다.
예시
<!DOCTYPE html>
<html>
<head>
<title>PHP Example</title>
</head>
<body>
<?php
// fetch the value of $_GET['user'] and returns 'not passed'
// if username is not passed
$username = $_GET['username'] ?? 'not passed';
print($username);
print("<br/>");
// Equivalent code using ternary operator
$username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
print($username);
print("<br/>");
?>
</body>
</html> 출력
not passed not passed