Increment a value with PHP ternary operator - php

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.

You'll want to use pre-increment here.
$x = ($x==2) ? 0 : ++$x;
Demo!

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...

Why don't use module operator for that ?
$x = ++$x % 2;

Related

Why is addition not working instead of increment operator in for loop in PHP?

I needed to increment the for loop by 7 by 7 and used the $x + 7 method as below. However, it didn't work.
for ($x = 1; $x <= 31; $x + 7) {
echo $x ."\n";
}
I solved the problem by redefining the variable as below but I am still wondering why the first method is not working.
for ($x = 1; $x <= 31; $x += 7) {
echo $x ."\n";
}
I usually use the $x++ method to increase the value. Why is $x + 7 different?
You can try: https://glot.io/snippets/g16a4it4il
$x + 7 does not alter x. It simply evaluates to 7 more than $x. To add 7 to $x, you can either:
$x += 7
or
$x = $x + 7
$x++ increments $x by 1. It is roughly equivalent to $x = $x + 1 or $x += 1. (Although when used in an expression, $x++ evaluates to the value of $x before the increment happens; for further information see What's the difference between ++$i and $i++ in PHP?)
The for loop works by changing $x every iteration until $x <= 31 is no longer true.
$x + 7 doesn't change $x, so it'll always remain 1

PHP: Use the short if-statement without else?

I'm a fan if the short if-version, example:
($thisVar == $thatVar ? doThis() : doThat());
I'd like to cut out the else-statement though, example:
($thisVar == $thatVar ? doThis());
However, it wont work. Is there any way to do it that I'm missing out?
You can't use it without the else. But you can try this:
($thisVar != $thatVar ?: doThis());
or
if ($thisVar == $thatVar) doThis();
The ternary operator is designed to yield one of two values. It's an expression, not a statement, and you shouldn't use it as a shorter alternative to if/else.
There is no way to leave out the : part: what value would the expression evaluate to if you did?
If you're calling methods with side effects, use if/else. Don't take short cuts. Readability is more important than saving a few characters.
hmm interesting, because executing the below code is valid. Observe:
for ($i = 1; $i <=10; $i++) {
if ($i % 2) {
echo $i;
}
}
The above code indeed, will output 13579
Notice no 'else' clause was used in the above.
If you wanted to inform the user of whether $i % 2 == FALSE ($i's divisor yielded remainder 0), you could include an else clause to print out the even numbers like shown below:
for ($i = 1; $i <=10; $i++) {
if ($i % 2) {
echo "$i is odd";
echo "<br />";
} else {
echo "$i is even";
echo "<br />";
}
}
Giving you the output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
I hope my amazingly easy to understand examples will help all newcomers to PHP, hands down the 'best' server-side scripting language for building dynamic web applications :-)
USE NULL TO SKIP STATEMENTS WHEN IT IS IN SHORTHAND
$a == $b? $a = 10 : NULL;
Just use logical operators : AND, OR, &&, ||, etc.
($thisVar === $thatVar) && doThis();
a frequent use is :
$obj = doSomething($params) or throw new \Exception('Failed to do');
Working for me:
$leftHand != $rightHand?doThis():null;
$leftHand == $rightHand?null:doThis();

PHP for loop : equal or smaller than - works, equal to - creates infinte loop

This code works
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
but if instead of " <= " I use simply " = " php gets into an infinite loop that timesout
<?php
for ($x = 0; $x = 10; $x++) {
echo "The number is: $x <br>";
}
?>
Is that expected behavior?
Yes, you're using an assignment operator instead of a comparison operator. Now there's no way for that loop to end.
Yes, it's expected.
You must use <= instead of = only
<= is a comparaison operator : http://php.net/manual/en/language.operators.comparison.php
= is an assignment operator : http://php.net/manual/en/language.operators.assignment.php

Double equals in for loop?

Why doesn't the double equals work in a PHP for loop? The following works:
$cnt = 5;
for ($z = 0; $z <= $cnt; $z++) {
echo $z."!<br />";
}
But why doesn't this work?
$cnt = 5;
for ($z = 0; $z == $cnt; $z++) {
echo $z."!<br />";
}
The loop executes only if the condition evaluates to true. At the first iteration, $z == $cnt is false, so the loop never executes.
A common loop strategy is to use a sentinel value:
$cnt = 5;
$stop = $cnt + 1;
for ($z = 0; $z != $stop; $z++) {
. . .
}
Note that the comparison is negative (!= or !==). Using a sentinel is usually unnecessary for numerical loop variables (I wouldn't recommend it for your posted code), but is useful for other situations (e.g., when $stop represents null, an illegal value, etc.). It's particularly helpful when the loop variable changes in a pattern that is not easy to characterize succinctly.
because on the first iteration $z != $cnt, so the loop stops immediately.
Let us look at this from the computer's perspective:
If I am a computer this is what you told me to do:
set $cnt = 5;
set $z = 0;
check if $z equals $cnt
if so do whatever is in the loop, then increment $z
Trouble is, 5 does not equal 0 and never will, so the loop will simply be skipped. If you had $cnt = $z+1 inside the loop this would be an infinite loop.
So, you see, == works just fine, it simply doesn't do what you think it should do.
Hope this helps!
A for loop works by looping until a condition is made false. In the first example the loop will execute until z = 5 after that z will not longer be less than or equal to cnt (z starts at 0 and increments through each loop). In the second example you have $z == $cnt as your condition, and since z = 0 and cnt = 5 the loop will stop automatically because the condition is made false. You can use not equals instead like following:
$cnt = 6;
for ($z = 0; $z != $cnt; $z++) {
echo $z."!<br />";
}
The syntax of for is:
for (<init>; <condition>; <increment>)
The loop tests <condition> before each iteration. If it's true, it executes that iteration; if it's false, the loop terminates.
In your case, since $z == $cnt is false before the first iteration, the loop terminates immediately.
To do what you want, invert the test. You also need to bump the end value up by one, since the original version used <=, not <. Note that in both cases, the loop executes $cnt+1 times, because you start from 0.
for ($z = 0; $z != $cnt+1; $z++)

Why is my conditional echo-ing the wrong thing

I have something like
just a snipplet
$i = 1; while (...) {
echo ($i % 5 == 1) ? 'class="first-col"' : ($i % 5 == 0) ? 'class="last-col"' : '';
$i++;
}
but even when $i % 5 == 1, I will get class="last-col" echo-ed is my logic right?
This is actually a CSS fix for IE so that I wont need to use nth-child. I am trying to target the 1st and last columns of my grid which contains 5 col/row
The ?: operator is left-associative, i.e. you have
echo ( ($i % 5 == 1) ? 'class="first-col"' : ($i % 5 == 0) ) ? 'class="last-col"' : '';
See http://php.net/manual/en/language.operators.comparison.php
It is best not to nest ternary operators.
Better use if / elseif / else constructs, they are more legible.
adding parenthesis helps:
echo (($i % 5 == 1) ? 'class="first-col"' : (($i % 5 == 0) ? 'class="last-col"' : ''));
For a start you're using nested ternary operations. I'd at least use brackets around the individual conditions to make it obvious what should be carried out first.

Categories