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'
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'
You must be logged in to post a comment.
That’s the ternary operator:
That line translates to
It’s an example of the conditional operator in PHP.
It’s the shorthand version of:
See Using If/Else Ternary Operators
http://php.net/manual/en/language.operators.comparison.php.
It’s a ternary operation which is not PHP or WordPress specific, it exists in most langauges.
So in this case the value of $page will be “default”, when $page is something similar to false â otherwise it will remain unchanged.
It means that if $page does not have a value (or it is zero), set it to ‘default’.
It means if the $page variable is not empty then assign the $page variable on the last line that variable or set it to ‘default’ page name.
It is called conditional operator
More verbose syntax of the last line is:
That’s the so-called conditional operator. It functions like an if-else statement,
so
does the same as