pidari
pidari

Reputation: 449

Ternary operator and GET condition

I have the following code:

$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
    if($currentPage < 1)
    {
        $currentPage = 1;
    }

I want to get rid of the if statement and do everything in one line. How can I do this and is it even possible to do it in the ternary operator?

Upvotes: 0

Views: 78

Answers (4)

NYG
NYG

Reputation: 1817

Maybe php’s null coalescing operator may make your line more readable:

$currentPage = max($_GET["page"] ?? 1, 1);

Remember that having a single line code logic may be good but if the price is to have a code hard to understand, it’s better to hit that enter button. You can read about the null coalescing operator here.

Upvotes: 0

worenga
worenga

Reputation: 5856

$currentPage = (isset($_GET['page']) && $_GET['page'] > 1) ? $_GET['page'] : 1;

Taken the liberty to adjust the logic a bit. Please take into account that this is harder to read and code is generally read more often than written.

Upvotes: 5

Jay Blanchard
Jay Blanchard

Reputation: 34416

It's not complex, just consider the logic:

  • is $_GET['page'] set and is it less than 1 then make $currentPage 1
  • if not, make $currentPage equal to $_GET['page']

$currentPage = (isset($_GET['page'] && $_GET['page'] < 1) ? 1 : $_GET['page'];

Upvotes: 3

tadman
tadman

Reputation: 211610

Why not do something like this:

$currentPage = max(intval($_GET['page']), 1);

That will screen out any garbage and make sure the page value is at least 1.

Upvotes: 2

Related Questions