Reputation:
I was just trying an small program but i am getting unexpected output.
for($i=20;!$i<20;$i--)
echo '*';
the expected output is *
as only for first case when $i=20
is false so !$i<20
should return true but the no of times loop is executing is equal to value of $i
.
I tried manipulating values and concluded when I set value of $i
in negative the loop gets infinite.
Further i tried this
echo 20<20;
output was nothing as expected then
echo !20<20;
output was 1
as expected
Now when it tried:
19<20
it is returning 1 but when i am trying
!19<20
it is returning 1
why did this occurred ??
I am running PHP on WAMP Server and my PHP Version 5.5.0
Note: I am not having any problem with for loop i can handle it so please don't answer correcting my loop rather I was confused with working of !
so please answer for it.
Upvotes: 0
Views: 49
Reputation: 3698
Try
for($i=20;!($i<20);$i--)
echo '*';
Problem was that '!$i' were executing first and then '<' operator work.
Upvotes: 0
Reputation: 1868
You need brackets to 'not' the right part:
for($i=20;!($i<20);$i--)
echo '*';
The example of !20<20
does this:
!20<20
!(true)<20 <- converts the type to bool so we can negate
false<20 <- negates the true to false
0<20 <- converts the false to an int to compare
true
And the example of !19<20
does this:
!19<20
!(true)<20 <- converts the type to bool so we can negate
false<20 <- negates the true to false
0<20 <- converts the false to an int to compare
true
Upvotes: 1