-1

This are two lines of codes. Could anyone tell me what the difference is between the first way and the second? I'd like both to do exactly the same thing.

   $test = isset($_POST['test'])?$_POST['test']:[];

if(isset($_POST['test'])){
    $test[] = $_POST['test'];
}

Thanks !

Yannick Bloem
  • 147
  • 2
  • 3
  • 12

3 Answers3

4

First one sets $test to an empty array if $_POST['test'] is unset. However, the second one does not set $test to a default value. In fact, if $_POST['test'] was unset, $test would be un-existent/undefined/etc.

You would need to run $test = []; at the beginning of the second one to archive the exact same result.

Dave Chen
  • 10,617
  • 8
  • 35
  • 67
0

the top line would be equivalent to

if(isset($_POST['test'])){
     $test = $_POST['test'];
}else{
     $test = [];
}
djbrick
  • 205
  • 1
  • 4
0

The first uses a ternary operator, which is a shorthand for if (X) then $a = b else $a = c, which sets $test to $_POST['test'] if it isn't empty, or $test to an empty array.

The second example doesn't have the else case, so it will leave $test undefined if $_POST['test'] is empty.

See also the ternary operator section of this page in the PHP manual http://www.php.net/manual/en/language.operators.comparison.php.

Thom Wiggers
  • 6,474
  • 1
  • 37
  • 58