-2

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'];
}
Mulan
  • 129,518
  • 31
  • 228
  • 259
GTS Joe
  • 3,612
  • 12
  • 52
  • 94

2 Answers2

2

Yes they are same.

$vn = condition ? expression1:expression2;

is same as

if(condition) {
    $vn = expression1;
}
else {
   $vn = expression2;
}
javaDeveloper
  • 1,403
  • 3
  • 28
  • 42
0

Your condition is okay. but make sure that you have caption key in $_POST array.

$caption = empty($_POST['caption']) ? NULL : $_POST['caption'];

OR

$caption = (isset($_POST['caption']) && $_POST['caption'] == '') ? $_POST['caption'] : NULL;

empty or isset functions are useful in that case.

$a = '';
var_dump(isset($a));      // TRUE
var_dump(empty($a));      // TRUE

isset() and empty() - what to use

Community
  • 1
  • 1
Ravi Hirani
  • 6,511
  • 1
  • 27
  • 42
  • Like this? $caption = isset($_POST['caption']) == '' ? NULL : $_POST['caption']; – GTS Joe Aug 12 '16 at 04:31
  • Why would you need to check if $_POST['caption'] is set? If $_POST['caption'] = '' (empty string) doesn't that automatically mean it is set? – GTS Joe Aug 12 '16 at 04:48
  • if caption key is **not exist** in $_POST array and if you write condition as **$_POST['caption'] == ''** then it will give you an **error**. – Ravi Hirani Aug 12 '16 at 04:55
  • I copied and pasted your code in my script and I still get the error: Notice: Undefined index: caption. – GTS Joe Aug 12 '16 at 05:06
  • Write your condition this way:- $caption = (isset($_POST['caption']) && $_POST['caption'] == '') ? $_POST['caption'] : NULL; – Ravi Hirani Aug 12 '16 at 05:20