PHP comparing boolean with integer [closed] - php

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
var_dump((int) true); // returns 1
var_dump(true > 0); // returns true
var_dump(true > - 1); // returns false
var_dump(1 > - 1); // returns true
Can somebody explain me in detail what the results of those two above are because it is comparing boolean with integer and it is confusing to me.

> is a numerical comparison operator, so PHP does a "loose comparison" and converts true to 1 or -1 in each case.
I imagine the following is happening internally:
When you ask if (true > 0), PHP first loosely tests if true==0, returns false, then it substitutes 1 for true and the comparison returns true.
When you ask if (true > -1), PHP first loosely test if true==-1, returns true, which implies (true > -1) must be false.
In short: don't do things like this.

This answer no longer satisfies the question as OP changed the question.
You shouldn't normally compare operands of different types, if you have some code that does this there is probably a mistake. The result may not make a lot of sense.
If you want to know the answer, just try it:
var_dump(true > 0); // gives true
var_dump(true > -1); // gives false

I figured out what is happening here by considering what Blazemonger has written.
Consider this:
var_dump(true == 0); // returns false
var_dump(true == 1); // true
var_dump(true == -1); // true
var_dump(true == -2); // true
So true is anything BUT zero.
For the > operator, PHP first tests for equality (==), so
true == X which is always true except for X = 0.
If the comparison yields true, then it cannot be greater, so true > X is always false except for X = 0.
Therefore:
var_dump(true > 0); // true
var_dump(true > 1); // false
var_dump(true > -1); // false
var_dump(true > -2); // false

Related

Check if given number is Even, Odd or Neither in PHP? [duplicate]

This question already has answers here:
Test if number is odd or even
(20 answers)
Closed 7 years ago.
How can I get if a number is even or odd or neither (have decimal, like 1.5) with PHP? I know that there are operators like *, /, but they did not work.
Here's a try (of course it did not) (work that's just to find if it's a even number):
function even($n) {
return (($n/2)*2 == $n);
}
echo even(1); // true (should be false)
echo even(2); // true
How about
function even($n) {
if (!is_int($n)) {return 'n';}
return !($n % 2);
}
even(1); // false;
even(2); // true;
even(1.5); // 'n'
The danger here is that 'n' will evaluate as false if used as a boolean. It might be better to return some specific constants instead of true or false. The OP didn't specify what the return values should be.
It is pretty simple. modulo (%) is the operator you want, it determines if there would be a remainder if x is divided by y... for example (3 % 2 = 1) and (4 % 2 = 0).
This has been asked before too - pretty common question - you really just need to see if your number, $n % 2 is equal to 0.
php test if number is odd or even
Check if given number is integer first. And bitwise & to check if it is even or odd. Here is an example...
if (is_int($n)) {
if ($n & 1) {
echo 'Odd!';
} else {
echo 'Even!';
}
} else {
echo "Not a Integer!";
}
Hope this is helpful.
Use the modulo operator (%) to determine whether the integer is divisible by 2. You also need abs() to handle negative numbers, and is_int() to handle the fact that the modulo operator doesn't correctly handle floating point numbers. An example implementation follows:
function is_even($num) {
return is_int($num) && abs($num % 2) == 0;
}
function is_odd($num) {
return is_int($num) && abs($num % 2) == 1;
}
// this last one seems self-explanatory, but if you want it, here it is
function is_neither_even_nor_odd($num) {
return !is_even($num) && !is_odd($num);
}
// Tests: The following should all output true:
var_dump(
is_even(0),
is_even(2),
is_even(-6),
is_even(51238238),
is_odd(1),
is_odd(-1),
is_odd(57),
is_neither_even_nor_odd(1.5),
is_neither_even_nor_odd(2.5),
is_neither_even_nor_odd(-0.5),
is_neither_even_nor_odd(0.00000001)
);
Here's a demo.
is_numeric returns true if the given variable is a number
is_int returns true if the given variable is an integer
The modulor operator % can be used to determine if an integer is even or odd:
$num % 2 == 0 // returns true if even, false if odd

PHP order of logical operators

I'm curious about how PHP handles conditional statements / order of operations with nesting. If I use the following if condition:
if(x == (1 || 2))
{
// do something
}
I would expect it to behave the same as
if(x == 1 || x == 2)
{
// do something
}
...but it doesn't. My first example seems like it would be a handy shorthand that makes pretty good sense, but it doesn't do what I expect. Can anyone shed some light on the issue? What exactly does PHP do with my first statement?
So for this piece of code:
if ($x == ( 1 || 2))
{
// do something
}
In PHP, any non-zero number is considered true. Disclaimer: This fact isn't necessarily true in other languages. So in PHP, 0 is the only number considered false. So you're asking if $x == true in the above piece of code.
Hence, whenever $x is any number other than 0 the statement inside the if will resolve as true. However, when $x = 0 then that is equivalent to saying false == true which of course will resolve as false.
This article might help: PHP: Booleans
Your shorthand is logically invalid. In almost every case you'll have to write out the full logical cases for all possibilities you want to test for.
I say 'almost' because in PHP you can do something ridiculous like:
if( in_array($x, array(1,2)) ) {
// code!
}
x == (1 || 2)
evaluates like this:
(1 (if its false) then testing for 2, if not, the expression returns true)
now it will become:
if(x==true)?
Another example taken from (PHP.NET):
// foo() will never get called as those operators are short-circuit
$b = (true || foo());
See here about the precedence of an operator
http://php.net/manual/en/language.operators.precedence.php
It will behave the same as math (think BEDMAS), with the brackets being executed first. So your example is behaving as:
if (x == ( 1 || 2)) {
//code
}
and because 1 and 2 are both non-zero values (thus both true), you get:
if (x == true) {
//code
}
Unfortunately to get what you want you'll need:
if (x == 1 || x == 2) {
//code
}
how would it make sense? you are asking the computer to execute the following logical expression:
if x == (1 || 2) which is same as x == (the result of 1 || 2)
so your expression would be x == true since 1 || 2 would return true
computers do whatever you tell them to do
if(x == (1 || 2))
{
// do something
}
OR and AND operations come back with TRUE or FALSE
you statement says - if x equals (true) - as 1 or 2 will always be true
- this just doesn't make sense...
In first if evaluate result of 1||2 and check that it equal to x
In second its like this or this or this
however in first you can see that var_dump(1 || 2) returns every time true so
$x = 3;
var_dump($x == 1 || 2);
if($x == 1 || 2){
echo 'inside if';
}
is also true so it will print inside if even $x is 3
so imo second way is way to go

IF statement not working with OR [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
For some odd reason, I can NOT debug this for the life of me..
$this->input->post('post_page') = 10.... I echo the variable and it does print 10 to the screen.
This keeps returning false when it should be true..
So... can someone help me out with this? I tried putting individual parentheses around each check AND changing the || to OR.. still nothing.
Here is my code nonetheless:
if($this->input->post('post_page') <> 10
|| $this->input->post('post_page') <> 25
|| $this->input->post('post_page') <> 50
|| $this->input->post('post_page') <> 75) {
return false;
}
<> is equivalent to NOT EQUAL.
10 is NOT EQUAL to 25 hence it will enter the if statement and return false;
In fact, it will ALWAYS enter that if statement regardless of number
You could instead do this:
if($this->input->post('post_page') <> 10
&& $this->input->post('post_page') <> 25
&& $this->input->post('post_page') <> 50
&& $this->input->post('post_page') <> 75) {
return false;
}
In psuedo code:
IF
MY NUMBER IS NOT 10
AND IT IS NOT 25
AND IT IS NOT 50
AND IT IS NOT 75
RETURN FALSE
Or even better:
$allowedNumbers = array(10,25,50,75);
if(!in_array($this->input->post('post_page'), $allowedNumbers)) {
return false;
}
much easier to add new items to the list too. Any number you add to the array will not return false.
PSEUDO CODE for this one:
ALLOWED NUMBERS ARE 10,25,50,75
IF(MYNUMBER IS NOT IN THE LIST OF ALLOWED NUMBERS)
RETURN FALSE
I think you should use
if(!($this->input->post('post_page') == 10
|| $this->input->post('post_page') == 25
|| $this->input->post('post_page') == 50
|| $this->input->post('post_page') == 75)) {
return false;
}
Translated in boolean:
false or true or true or true.
The expression is true, therefore it returns false.
( #
(A is not B) # IS ALWAYS TRUE
OR (A is not C) # --------------------------
OR (A is not D) # Unless 2 conditions (AND):
OR (A is not E) # . A is not B
) # . B = C = D = E
So yes, in your case, this will always be FALSE, sorry for you.

Explain php if statement

Can someone please explain in detail what these if statements are doing?
What does the three === signs to in the first one, and What does the single & in the second mean?
$aProfile = getProfileInfo($iId);
if($aProfile === false)
return false;
if(!((int)$aProfile['Role'] & $iRole))
return false;
=== tests for type-safe equality.
'3' == 3 will return true, but '3' === 3 will not, because one's a string and one's an integer. Similarly, null == 0 will return true, but null === 0 will not; 10.00 == 10 will return true, but 10.00 === 10 will not.
& is the bitwise AND operator. It returns a bitmask in which a bit is set if both the corresponding bits are set from the original two bitmasks.
For example:
$x = 5;
$y = 17;
echo $x & $y;
causes 1 to be echoed. $x is ...000101, $y is ...010001. The only bit that is set in both of them is the rightmost one, so you get ...000001, which is 1.
Here's a good guide to PHP operators:
http://www.tuxradar.com/practicalphp/3/12/3
See the section on bitwise operators for info on the &.

Difference between & and && in PHP

I am confused with & and &&. I have two PHP books. One says that they are same, but the another says they are different. I thought they are same as well.
Aren't they same?
& is bitwise AND. See Bitwise Operators. Assuming you do 14 & 7:
14 = 1110
7 = 0111
---------
14 & 7 = 0110 = 6
&& is logical AND. See Logical Operators. Consider this truth table:
$a $b $a && $b
false false false
false true false
true false false
true true true
The other answers are correct, but incomplete. A key feature of logical AND is that it short-circuits, meaning the second operand is only evaluated if necessary. The PHP manual gives the following example to illustrate:
$a = (false && foo());
foo will never be called, since the result is known after evaluating false. On the other hand with
$a = (false & foo());
foo will be called (also, the result is 0 rather than false).
Matthew's answer about how Logical And && operator is the biggest difference; logical comparison will stop when it will find something that breaks the chain. In addition, one more big difference it the result type/value.
tl;dr
By using the Logical And &&, it will always return a Boolean type/value, true or false.
false & 1 // int(0)
false && 1 // bool(false)
It is important to use Boolean type/values when returning a function with a logical result, because someone can use the Identical comparison operator === to compare the results (which is high likely to happen) and it will fail if you use something like this:
(false & 1) === false // bool(false)
(true & true) === true // bool(false)
Never use Bitwise And & when you need to make a logical comparison and especially when returning values from functions with logical results. Instead use the Logical And &&:
(false && 1) === false // bool(true)
(true && true) === true // bool(true)
When comparing characters, Logical And && will always result to true, even with NUL character, unless if it's converted to an integer:
'A' && 'B' // bool(true)
'A' && 0 // bool(false)
'A' && '\0' // bool(true)
'A' && (int)'\0' // bool(false)
If you use the Bitwise And & with characters, it will result the character corresponding to the Bitwise And operation between those two characters:
'A' & 'B' // string(1) "#"
01000001 // ASCII 'A'
&
01000010 // ASCII 'B'
=
01000000 // ASCII '#'
Beware the usage of the Bitwise And & when using with types other than Integers and Characters (which are special kind of integers). For example, if you use it with real numbers float/double, then it can result to 0 even if both operands are NOT 0:
1.0 & 1.0 // int(1)
2.0 & 1.0 // int(0)
1.0 && 1.0 // bool(true)
2.0 && 1.0 // bool(true)
In addition, if we go at assembly instructions level, we can see that difference and how the compiler manages to handle so the Logical And && uses cmp <var>, 0 to compare and does not continue executing if one operand fails; Bitwise And uses and <var1>, <var2> to make a bitwise result and then test if it's of 0 value. I know this question is tagged for php and php behavior may be different than c, but I'll use a small c program to demonstrate how compiler behaves when using Logical and Bitwise And.
Let's assume we have a program in c that uses both Bitwise and Logical And:
int a = 0;
int b = 1;
int c = 2;
if (a & b)
c = 3;
if (a && b)
c = 4;
The compiler will generate the following assembly opcodes (W32Dasm result for x86; I have changed the memory addresses with <variable> names for simplicity and to be more understandable):
:0229 mov <a>, 0
:0230 mov <b>, 1
:0237 mov <c>, 2
// if (a & b) begins
:023E mov eax, <a>
:0241 and eax, <b> // a bitwise and b, result stored to eax
:0244 test eax, eax // test eax and set ZeroFlag if equals to 0
:0246 je 024F // >--- Jump if ZeroFlag is set
:0248 mov <c>, 3 // | or set c = 3
// if (a && b) begins |
:024F cmp <a>, 0 // <--- compare a to 0 and sets ZeroFlag if difference is 0
:0253 je 0262 // >--- Jump if ZeroFlag is set (a == 0)
:0255 cmp <b>, 0 // | compare b to 0 and sets ZeroFlag if differemce is 0
:0259 je 0262 // | >--- Jump if ZeroFlag is set (b == 0)
:025B mov <c>, 4 // | | or set c = 4
:0262 <program continues> // <--- <---
The compiler not only uses different instructions to compare between the Logical and Bitwaise And, but at the line :0253 in if (a && b) logical comparison, we see that if a == 0 then it jumps and does not check for the rest operands.
So, I disagree to animuson's comment:
They are both the same thing, they're just used for two different
things to accomplish the same task. – animuson Mar 4 '10 at 1:42
They are not the same thing and both are/(should be) used for specific tasks depending on the programs' logic/flow.
AND operation:
& -> will do the bitwise AND operation , it just doing operation based on
the bit values.
&& -> It will do logical AND operation. It is just the check the values is
true or false. Based on the boolean value , it will evaluation the
expression
As the others are saying, a single & is bit-wise. It basically converts the left-hand value into its bits representation, and the right hand side into bits representation as well, then performs logical AND between them and outputs the result.
Double && is either true or false, (in some languages 0 or 1) if both left and right side are true (or non-zero).
I'd also add that this is not just in PHP. It is like that in many many other languages as well, like C, Java, Ruby, etc.
&& is & performed on operands reduced to either 1 or 0.
(In other words, && is a bitwise operator under the caveat that it changes its operands. That is, logical operations are a subset of bitwise operations.)

Categories