Search code examples
phpdefault-value

Set default value of a variable in PHP


Is there a summarised way to write this code

if(y) {x=y;} else {x="default"}

I tried

$x=$y||"default"

but it fails.


Solution

  • Use the PHP ternary operator, like so:

    $x = $y ?: "default";
    

    If you are using PHP < 5.3, you'll need to use the full ternary form like so:

    $x = $y ? $y : "default";