GTS Joe GTS Joe - 1 year ago 77
PHP Question

PHP Ternary Expression / If Statement

I'm learning ternary expressions in PHP and was wondering if someone could verify that the following two blocks of code are the same as far as what is the outcome?

$caption = $_POST['caption'] == '' ? NULL : $_POST['caption'];


Is the above the same as the below?

if ( $_POST['caption'] == '' ) {
$caption = NULL;
}
else {
$caption = $_POST['caption'];
}

Answer Source

Yes they are same.

$vn = condition ? expression1:expression2;

is same as

if(condition) {
    $vn = expression1;
}
else {
   $vn = expression2;
}