블로그

php, javascript 정오 비교, 3항 연산자

Code › Web · 2019-05-07

Equality comparisons and sameness
type comparison tables

* Javascript 정오 비교표 (정오표)
https://dorey.github.io/JavaScript-Equality-Table/
   https://developer.mozilla.org/ko/docs/Web/JavaScript/Equality_comparisons_and_sameness

* php 비교표
https://phpcheatsheets.com/compare/
   https://www.php.net/manual/en/types.comparisons.php
   https://www.php.net/manual/en/language.operators.comparison.php

 

//-----------------------------------------------------------------------------

 
 
 
 
 is_countable($v) ?

$v
isset()
is_null()
empty()
count()
sizeof()

NULL
FALSE
TRUE
TRUE
0
0

''
TRUE
FALSE
TRUE
0
0

' '
TRUE
FALSE
FALSE
0
0

0
TRUE
FALSE
TRUE
0
0

'0'
TRUE
FALSE
TRUE
0
0

0
TRUE
FALSE
TRUE
0
0

'\0'
TRUE
FALSE
FALSE
0
0

1
TRUE
FALSE
FALSE
0
0

FALSE
TRUE
FALSE
TRUE
0
0

TRUE
TRUE
FALSE
FALSE
0
0

[]
TRUE
FALSE
TRUE
0
0

 

//----------------------------------------

isset(), empty(), is_null() 함수 실행 결과 

www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/

Value of variable ($var)
isset($var)
empty($var)
is_null($var)

“” (an empty string)
bool(true)
bool(true)
 

” ” (space)
bool(true)
 
 

FALSE
bool(true)
bool(true)
 

TRUE
bool(true)
 
 

array() (an empty array)
bool(true)
bool(true)
 

NULL
 
bool(true)
bool(true)

“0” (0 as a string)
bool(true)
bool(true)
 

0 (0 as an integer)
bool(true)
bool(true)
 

0.0 (0 as a float)
bool(true)
bool(true)
 

var $var; (a variable declared, but without a value)
 
bool(true)
bool(true)

NULL byte (“\ 0”)
bool(true)
 
 

 

//=================
< 삼항 연산자 >

[ PHP ]
* 다음은 2개는 동일한 출력값

echo ( isset($val) ? $val : null ); // 삼항 연산자(Ternary Operator )
echo ( $val ?? null ); // NULL 병합 연산자(Null Coalescing Operator)
- $val 이 undefined 상태이면 null
- $val=0 이면 0을 출력

//========
echo ( isset($val) ?  : null );//주의!! 권장하지 않음
    - $val=0 이면 1을 출력

 

 

//-----------------------------------------------------------------------------
* 3항 연산자 (Ternary Operator)
     cond ? expr1 : expr2

 $user = load_user() ? load_user() : false;

    - 줄임
 $user = load_user() ?: false;

//-------------------------------------
* null 병합 연산자 (Null Coalescing Operator) :  
    result = variable ?? expression
    - variable이 선언되지 않았거나, null 경우 expression 선택

 $result = isset($_GET['value']) ? $_GET['value'] : 'foo';

 $result = $_GET['value'] ?? 'foo';

//-------------------------------------
* Null 병합 할당 연산자  (Null Coalescing Assignment operator) :  php 7.4 이상
    null 병합 연산자를 더 줄임
    ??=

 $value = $value ?? 'foo';

 $value ??= 'foo';

//-----------------------------------------------------------------------------
//==============
[ Javascript ] 
조건부 삼항 연산자(conditional ternary operator) 

condition ? exprIfTrue : exprIfFalse

주의! php 처럼 
condition ? : exprIfFalse
줄임을 허용하지 않음

대체 : || 이용
condition || exprIfFalse

    var ret = ret2 = false;
    // var ret = ret2 = true;

    ret = ret ? ret : 'ifFalse';
    ret2 = ret2 || 'ifFalse';

    console.log(ret, ret2);

알림