2

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 ?
Noman Ur Rehman
  • 6,707
  • 3
  • 24
  • 39
  • this is wrong $value = "".$text; If $text is not set it will generate an error if used directly – Anonymous Duck May 07 '15 at 07:45
  • 1. afaik, no 2. yes, you can't just not consider the isset check 3. afaik, no. – Masiorama May 07 '15 at 07:46
  • 1. That is already a ternary operator which is pretty much the short syntax for if-else 2.Your code will throw a E_NOTICE 3. Yes then you will end up with the ternary operator – Rizier123 May 07 '15 at 07:47
  • Read this, this may be helpful for you .http://stackoverflow.com/questions/1506527/how-do-i-use-shorthand-if-else –  May 07 '15 at 07:50

3 Answers3

1

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

1

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.

ksbg
  • 3,214
  • 1
  • 22
  • 35
0

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.

Levi Morrison
  • 19,116
  • 7
  • 65
  • 85