Question

With this test page:

$page   = (int) $_GET['page'] ?: '1';
echo $page;

I don't understand the output I'm getting when page is undefined:

Request   Result
?page=2   2
?page=3   3
?page=    1
?         error: Undefined index page

Why the error message? It's PHP 5.3; why doesn't it echo "1"?

Was it helpful?

Solution

The proper way (in my opinion) would be:

$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;

Even if you used the new style, you would have problems with ?page=0 (as 0 evaluated to false). "New" is not always better... you have to know when to use it.

OTHER TIPS

Unfortunately you cannot use it for the purpose you'd like to use it for:

Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

So you'll still have to use isset or empty() - the ?: operator does not include an isset check. What you need to use is:

$page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;

Just for completeness, another way to achieve it is to pull operator rank:

 $page = (int)$_GET["page"]  or  $page = 1;

Many people perceive this as unreadable however, though it's shorter than isset() constructs.

Or if you are using input objects or any other utility class:

 $page = $_GET->int->default("page", 1);

It's because you're trying to typecast something that's undefined: (int) $_GET['page']

Remove the (int) or set the typecast after the conditional line.

If bloat is your concern, how about a helper function?

function get_or($index, $default) {
    return isset($_GET[$index]) ? $_GET[$index] : $default;
}

then you can just use:

$page = get_or('page', 1);

which is clean and handles undefined values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top