Search code examples
phpwordpressternary-operatorconditional-operatorlanguage-construct

What does this syntax ( page = $page ? $page : 'default' ) in PHP mean?


I'm new to PHP. I came across this syntax in WordPress. What does the last line of that code do?

$page = $_SERVER['REQUEST_URI'];
$page = str_replace("/","",$page);
$page = str_replace(".php","",$page);
$page = $page ? $page : 'default'

Solution

  • It's an example of the conditional operator in PHP.

    It's the shorthand version of:

    if (something is true ) {
        Do this
    }
    else {
        Do that
    }
    

    See Using If/Else Ternary Operators http://php.net/manual/en/language.operators.comparison.php.