views:

181

answers:

7

i'm new to php. I came across this syntax in wordpress. Can anyone explain to me the last line of that code?

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

the last line(bolded). thanks

+7  A: 

That's the conditional operator: http://php.net/manual/en/language.operators.comparison.php

That line translates to

if($page)
    $page = $page;
else
    $page = 'default';
echo
+2  A: 

It means that if $page has not value (or it is zero), set it to 'default'.

wallyk
+1  A: 

more verbose syntax of the last line:

if ($page)
{
    $page = $page;
}
else
{
    $page = 'default';
}
Karsten
+1  A: 

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

Sarfraz
It's misnamed **the** ternary operator where it really is just **a** ternary operater. Granted that in most language it is the only ternary operator implemented but that doesn't preclude the creation of other operators that takes 3 arguments. A language could for example have an operator for declaring functions, much like Forth's `:` operator, that operates on function name, parameter list and code block. That would also be a ternary operator.
slebetman
A: 

That's the so-called conditional operator. It functions like an if-else statement, so

$page = $page ? $page : 'default';

does the same as

if($page)
{
    $page = $page;
}
else
{
    $page = 'default';
}
Douwe Maan
+3  A: 

It's a ternary operation which is not PHP or Wordpress specific, it exists in most langauges.

(condition) ? true_case : false_case 

So in this case the value of $page will be "default", when $page is something similar to false — Otherwise it will remain unchanged.

Nils Riedemann
+5  A: 

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
}

http://www.totallyphp.co.uk/tutorials/using_if_else_ternary_operators.htm http://php.net/manual/en/language.operators.comparison.php

Cups