5
votes

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"?

5
Pretty much unrelated, but you really want 1, not '1'.ThiefMaster
On the command line, this prints 1 just fine: php -r 'echo (int)$foo ?: 1;' (PHP 5.3.3, notice the lack of error due to error reporting being silent). Can you try to run that and see what it does? Does it really say "error, undefined index"?deceze♦
It is and has always been a notice. That "error message" is certainly hand-written.ThiefMaster

5 Answers

12
votes

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.

3
votes

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;
3
votes

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);
2
votes

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.

1
votes

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.