Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP 5.3 ?: operator

Tags:

php

php-5.3

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

like image 205
Isis Avatar asked Nov 17 '10 23:11

Isis


1 Answers

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.

like image 152
Felix Kling Avatar answered Sep 21 '22 07:09

Felix Kling