Alternate for shorthand if else

107 Views Asked by At

I have seen a lot of people being used to do this in their code:

$value = isset($text) ? $text : "";

This code essentially means set $value to $number(if it is set) else set $value to ""

I experimented a bit and came up with a much cleaner syntax:

$value = "".$text;

Apart from when $text is undefined, this code covers all the cases and works the same way.

So, my questions are:

  1. Is there a better, shorter, cleaner way to do $value = isset($text) ? $text : "";
  2. Am I wrong to assume my approach works the same way?(apart from isset case)
  3. Can my approach be modified to address the isset case as well ?
3

There are 3 best solutions below

0
Akatsuki Pain On

ternary is already the shortest code for that brother. you already got it.

0
ksbg On

Yes, it does give the same result, but only if $test contains an empty string. If $test is not initialized, it generates an error, yet checking that is the very purpose of this ternary if statement.

If you would want to do the same without using the if statement, you would still need to check if $test is set, and if not, initialize it using an empty string, which would require another if-statement.

To sum up: No, there does not seem to be a better way to achieve the same.

0
Levi Morrison On

As of PHP 7.0 there is a null coalescing operator that will make this shorter:

// ternary
$value = isset($text) ? $text : "";

// null coalesce
$value = $text ?? "";

Your concatenation statement will generate an error if the variable is not defined.