Try :
$page = $_GET['page'] ? $_GET['page'] : 0;
Question
This is a really basic question and I appoligize for asking, but it would be really usefull for me to understand, so I can use this method in the future,
How would I turn
if($_GET['page']) {
$page = $_GET['page'];
} else {
$page = 0;
}
Into a simple 1 line shorthand result ?
La solution
Try :
$page = $_GET['page'] ? $_GET['page'] : 0;
Autres conseils
A real simple shorthand for your statement would be just
$page = $_GET['page'];
which would be enough for the most cases.
But you really meant if (isset($_GET['page']))
, not just if ($_GET['page'])
so, one of these ternaries can be used.
However, for the variables like $page
I would use different strategy, called "define your variables!"
So, for the essential variables I would define them all first.
$page = 0;
and then, when processing request, would set it with some value, is present
if(isset($_GET['page'])) {
if (!is_numeric($_GET['page'])) {
throw new HTTP400()
} else {
$page = $_GET['page'];
}
}
$page=(isset($_GET['page']))?$_GET['page']:0;
I suggest you use isset() as well for better error handling.
$page = (isset($_GET['page'])) ? $_GET['page'] : 0;
I would add standard check:
$page=isset($_GET['page'])?$_GET['page']:0;