PHP에서 "if / else"의 약어로 삼항 연산자 (? :)를 어떻게 사용합니까?
이 페이지 의 예제 를 기반으로 아래에 작동 및 작동하지 않는 코드 샘플이 있습니다.
if
문을 사용하는 작업 코드 :
if (!empty($address['street2'])) echo $address['street2'].'<br />';
삼항 연산자를 사용하는 작동하지 않는 코드 :
$test = (empty($address['street2'])) ? 'Yes <br />' : 'No <br />';
// Also tested this
(empty($address['street2'])) ? 'Yes <br />' : 'No <br />';
업데이트
브라이언의 팁 후, 에코 $test
가 예상 된 결과를 출력 한다는 것을 알았습니다 . 다음은 매력처럼 작동합니다!
echo (empty($storeData['street2'])) ? 'Yes <br />' : 'No <br />';
그만큼
(condition) ? /* value to return if condition is true */
: /* value to return if condition is false */ ;
구문은 ?
다음과 같은 방식으로 코드를 실행할 수 없기 때문에 "약식 if"연산자 ( 조건부 연산자라고 함)가 아닙니다.
if (condition) {
/* condition is true, do something like echo */
}
else {
/* condition is false, do something else */
}
귀하의 예에서는이 비어 있지 않을 echo
때 문을 실행하고 $address
있습니다. 조건부 연산자와 같은 방식으로이 작업을 수행 할 수 없습니다. 그러나 수행 할 수있는 작업 echo
은 조건부 연산자의 결과입니다.
echo empty($address['street2']) ? "Street2 is empty!" : $address['street2'];
그러면 "Street is empty!"가 표시됩니다. 비어 있으면 street2 주소를 표시합니다.
PHP 7 이상
PHP 7 부터이 작업은 다음 과 같이 Null 병합 연산자를 사용하여 간단히 수행 할 수 있습니다 .
echo !empty($address['street2']) ?? 'Empty';
기본 참 / 거짓 선언
$is_admin = ($user['permissions'] == 'admin' ? true : false);
조건부 환영 메시지
echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';
조건부 항목 메시지
echo 'Your cart contains '.$num_items.' item'.($num_items != 1 ? 's' : '').'.';
삼항 연산자는 및 if / else 블록의 약어입니다. 작업 코드에는 else 조건이 없으므로 이에 적합하지 않습니다.
다음 예제가 작동합니다.
echo empty($address['street2']) ? 'empty' : 'not empty';
당신이 찾고있는 삼항 연산자 일명 Elvis 연산자 (google it : P)입니다.
echo $address['street2'] ?: 'Empty';
변수의 값을 반환하거나 변수가 비어 있으면 기본값을 반환합니다.
참고 중첩 된 조건 연산자를 사용하는 경우, 당신은 괄호를 사용할 수 있습니다 가능한 문제를 피하기 위해!
PHP가 최소한 Javascript 또는 C #과 동일한 방식으로 작동하지 않는 것 같습니다.
$score = 15;
$age = 5;
// The following will return "Exceptional"
echo 'Your score is: ' . ($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average'));
// The following will return "Horrible"
echo 'Your score is: ' . ($score > 10 ? $age > 10 ? 'Average' : 'Exceptional' : $age > 10 ? 'Horrible' : 'Average');
Javascript와 C #의 동일한 코드는 두 경우 모두 "Exceptional"을 반환합니다.
두 번째 경우, PHP가하는 일은 (또는 적어도 내가 이해하는 것입니다) :
- 이다
$score > 10
? 예 - 이다
$age > 10
? 아니요, 따라서 현재$age > 10 ? 'Average' : 'Exceptional'
는 '예외'를 반환합니다. - 그런 다음 전체 문을 중지하고 'Exceptional'을 반환하는 대신 다음 문을 계속 평가합니다.
'Exceptional' ? 'Horrible' : 'Average'
'Exceptional'이 진실이므로 'Horrible'을 반환 하는 다음 문이됩니다.
From the documentation: http://php.net/manual/en/language.operators.comparison.php
It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious.
Conditional Welcome Message
echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';
Nested PHP Shorthand
echo 'Your score is: '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );
You can do this even shorter by replacing echo
with <?= code ?>
<?=(empty($storeData['street2'])) ? 'Yes <br />' : 'No <br />'?>
This is useful especially when you want to determine, inside a navbar, whether the menu option should be displayed as already visited (clicked) or not:
<li<?=($basename=='index.php' ? ' class="active"' : '')?>><a href="index.php">Home</a></li>
Here are some interesting examples, with one or more varied conditions.
$value1 = '1';
$value2 = '2';
$value3 = '3';
// 1 Condition
$v1 = ($value1 == '1') ? TRUE : FALSE;
var_dump($v1);
echo "<br>";
// 2 Conditions
$v2 = ($value1 == '' ? TRUE : ($value2 == '2' ? TRUE : FALSE));
var_dump($v2);
echo "<br>";
// 3 Conditions
$v3 = ($value1 == '' ? TRUE : ($value2 == '' ? TRUE : ($value3 == '3' ? TRUE : FALSE)));
var_dump($v3);
echo "<br>";
// 4 Conditions
$v4 = ($value1 == '1') ? ($value2 == '2' ? ($value3 == '3' ? TRUE : 'FALSE V3') : 'FALSE V2') : 'FALSE V1' ;
var_dump($v4);
echo "<br>";
I think you used the brackets the wrong way. Try this:
$test = (empty($address['street2']) ? 'Yes <br />' : 'No <br />');
I think it should work, you can also use:
echo (empty($address['street2']) ? 'Yes <br />' : 'No <br />');
There's also a shorthand ternary operator and it looks like this:
(expression1) ?: expression2 will return expression1 if it evaluates to true or expression2 otherwise.
Example:
$a = 'Apples';
echo ($a ?: 'Oranges') . ' are great!';
will return
Apples are great!
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
From the PHP Manual
'code' 카테고리의 다른 글
Python 반복기에서 마지막 항목을 가져 오는 가장 깨끗한 방법 (0) | 2020.08.21 |
---|---|
Restful 백엔드 용 Ember.js 또는 Backbone.js (0) | 2020.08.21 |
임의의 부울 값을 반환하는 가장 좋은 방법 (0) | 2020.08.21 |
Rails에서 파일 업로드를 어떻게 테스트합니까? (0) | 2020.08.20 |
콘솔에서 Subversion을 사용할 때 비밀번호를 저장하는 방법 (0) | 2020.08.20 |