user933791
user933791

Reputation: 381

Increment a value with PHP ternary operator

How can I increment $x using the ternary operator?

I've tried $x = $x==2 ? 0 : ++; but obviously it didn't work.

if($x == 2 ){ 
    $x=0; 
}else{ 
    $x++; 
}

Thanks.

Upvotes: 0

Views: 2459

Answers (3)

Dani
Dani

Reputation: 1

Why don't use module operator for that ?

$x = ++$x % 2;

Upvotes: -2

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76413

The best way to do this would be:

$x = $x === 2 ? 0 : $x+1;

If you insist on using a ternary just to increment the var:

$x += $x === 2 ? $x*(-1) : 1;//or hard-code -2 instead of $x*(-1)

This either adds 1 to $x or adds $x*-1 to $x ($x + (-$x) is 0). On the whole, though, I'd like to add that ternary (especially in PHP) should be avoided as much as possible. In this case, writing:

if (++$x === 3)
{
    $x = 0;
}

Does exactly the same thing, and isn't that much more code, though it does look a lot nicer. Even so, the increment in an if statement is still messy, best increment beforehand, or:

$x = $x === 2 ? -1 : $x;
$x++;

If you've got a strange preference for ternaries... and if it has to be a one-liner:

$x = ($x ===2 ? -1 : $x) +1;

works, too... but there's a code-golfing site for these kind of things...

Upvotes: 7

Amal Murali
Amal Murali

Reputation: 76636

You'll want to use pre-increment here.

$x = ($x==2) ? 0 : ++$x;  

Demo!

Upvotes: 10

Related Questions