Need exact reason for this logically condition failed - php

Why below code is printing the "here", it should be "there"
$a = "171E-10314";
if($a == '0')
{
echo "here";
}
else
{
echo "there";
}

PHP automatically parses anything that's a number or an integer inside a string to an integer. "171E-10314" is another way of telling PHP to calculate 171 * 10 ^ -10314, which equates to (almost) 0. So when you do $a == '0', the '0' will equate to 0 according to PHP, and it returns true.
If you want to compare strings, use the strcmp function or use the strict comparator ===.

when you use the == comparison, PHP tries to cast to different data types to check for a match like that
in your case:
'0' becomes 0
"171E-10314" is still mathematically almost 0 but I think PHP just rounds it to 0 due to the resolution of float.
check this link for a visual representation:
http://www.wolframalpha.com/input/?i=171E-10314

As per the answers given I tried to convert the string into numerical:
$a = "171E-10314" + 0;
print $a;
And I got output as 0.
Thats why it is printing here.

Use === /*(this is for the 30 character)*/

Related

PHP: Strange behaviour with variable assignment

I'm declaring a var $t and assigning it a value of 0. I then reassign $t a new value of test. It then appears that $t is both 0 AND test. Here's the code:
$t = 0;
$t = "test";
if($t == 0 && $t == "test"){
echo "unexpected";
}else{
echo "expected";
}
The output is:
"unexpected"
Can someone please explain what is going on here? Is $t really two different values (0 and test) at the same time or am I missing something?
This "strange" behaviour results in because of PHP's type juggling. Since you're using loose comparison == to compare to an integer 0 the string test is being converted to an integer, which results in conversion to 0. See the Loose comparison == table. There in the row with the string php you'll see that it equals to the integer 0, which applies to all strings.
You should be using strict (type) comparison operators, i.e. ===.
You're not appending or concatenating so it shouldn't be. Try the identical comparison operator instead.
if($t === 0 && $t === "test"){
....
}
PHP MANUAL STATES:
The value is given by the initial portion of the >string. If the string starts with valid numeric >data, this will be the value used. Otherwise, the >value will be 0 (zero). Valid numeric data is an >optional sign, followed by one or more digits >(optionally containing a decimal point), >followed by an optional exponent. The >exponent is an 'e' or 'E' followed by one or >more digits.
http://il.php.net/manual/en/language.types.string.php#language.types.string.conversion
So $t == 0 is true. You have to use strict comparison ===
Hey buddy use "===" operator for your comparison.
In php we can assign any value to a simple variable, it holds numeric, float, character, string, etc.
So always use "===" operator for unique or same value matching.

Comparison of 0 to a string fails

Update: 0 isn't using the default value, after testing it was the condition that was failing as suggested by the answers.
function test($value='A') {
if ($value != 'A') {
echo 'OK';
}
else {
echo 'NOT OK';
}
}
test(); // Outputs NOT OK
test('A'); // Outputs NOT OK
test(0); // Outputs NOT OK, Should output OK?
test('0'); // Outputs OK
test(null); // Outputs OK
test(false); // Outputs OK
This is kind of throwing one of my functions. I was surprised to see only 0 does this and null works fine. Does anyone know why PHP is interpreting 0 as the default value?
In PHP, comparing a string 'A' with a number 0 causes a change of the string to a number. In this case 'A' gets converted to 0, so of course 0 == 0.
See here for details.
For completeness, the fix, from the same linked documentation is
use strict comparison operators (===, !==)
comparison operators
Change your test to:
if ($value !== 'A') {
When you use == or != to compare a number and a string, it coerces the string to a number. The string 'A' converts to 0, so they're equal.
As you using loosely comparison operator PHP is trying to implicitly convert the 0 into the string. Use !== for strict comparison.
DEMO.

Difference Between $a = 0 and $a = '0' in PHP

I had an if statement similar to the following in my code and it took me forever to figure out what the problem was.
$a = 0;
if($a == 'something')
{
//this was being output when I didn't want it to be
}
Using
$a = '0';
fixed it, but I don't really know what's going on here.
One's a string, one's an integer. PHP will translate between the two as needed, unless you're using the 'strict' operators:
(0 == '0') // true
(0 === '0') // false (types don't match).
In your case, you'r comparing an integer 0 to a string 'something'. PHP will convert the string 'something' to an integer. If there's no digits in there at all, it'll conver to an integer 0, which makes your comparison true.
Just a guess, but I assume it's trying to cast the string to an integer.
intval('something') I expect will return 0.
You were comparing a numeric value ($a = 0;) to a string. In this case the string is casted to number, and PHP cast strings to 0 if there is no number in the beginning, so is true.
In the other case however you campared two strings, which are different, so it is false.

is_int and GET or POST

Why does is_int always return false in the following situation?
echo $_GET['id']; //3
if(is_int($_GET['id']))
echo 'int'; //not executed
Why does is_int always return false?
Because $_GET["id"] is a string, even if it happens to contain a number.
Your options:
Use the filter extension. filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT) will return an integer typed variable if the variable exists, is not an array, represents an integer and that integer is within the valid bounds. Otherwise it will return false.
Force cast it to integer (int)$_GET["id"] - probably not what you want because you can't properly handle errors (i.e. "id" not being a number)
Use ctype_digit() to make sure the string consists only of numbers, and therefore is an integer - technically, this returns true also with very large numbers that are beyond int's scope, but I doubt this will be a problem. However, note that this method will not recognize negative numbers.
Do not use:
is_numeric() because it will also recognize float values (1.23132)
Because HTTP variables are always either strings, or arrays. And the elements of arrays are always strings or arrays.
You want the is_numeric function, which will return true for "4". Either that, or cast the variable to an int $foo = (int) $_GET['id']...
Checking for integers using is_int($value) will return false for strings.
Casting the value -- is_int((int) $value) -- won't help because strings and floats will result in false positive.
is_numeric($value) will reject non numeric strings, but floats still pass.
But the thing is, a float cast to integer won't equal itself if it's not an integer. So I came up with something like this:
$isInt = (is_numeric($value) && (int) $value == $value);
It works fine for integers and strings ... and some floating numbers.
But unfortunately, this will not work for some float integers.
$number = pow(125, 1/3); // float(5) -- cube root of 125
var_dump((int) $number == $number); // bool(false)
But that's a whole different question.
How i fixed it:
$int_id = (int) $_GET["id"];
if((string)$int_id == $_GET["id"]) {
echo $_GET["id"];
}
It's probably stored as a string in the $_GET, cast it to an int.
Because $_GET is an array of strings.
To check if the get parameter contains an integer you should use is_numeric()
Because $_GET['id'] is a string like other parts of query string. You are not converting it to integer anywhere so is_int return false.
The dirty solution I'm using is this:
$val = trim($_GET['id']);
$cnd = ($val == (int)$val);
echo $cnd ? "It's an int" : "Not an int";
Apart from the obvious (ugly code that hides its workings behind specifics of the php engine), does anybody know cases where this goes wrong?
Prabably best way to check if value from GET or POST is integer is check by preg_match
if( preg_match('/^[0-9]+$/', $_GET['id'] ){
echo "is int";
}
You can possibly try the intval() which can be used to test the value of your var. e.g
If(intval($_GET['ID']==0)
The function will check if the var is integer and return TRUE if not FALSE

PHP: Check if 0?

I am using a class which returns me the value of a particular row and cell of an excel spreadsheet. To build up an array of one column I am counting the rows and then looping through that number with a for() loop and then using the $array[] = $value to set the incrementing array object's value.
This works great if none of the values in a cell are 0. The class returns me a number 0 so it's nothing to do with the class, I think it's the way I am looping through the rows and then assigning them to the array... I want to carry through the 0 value because I am creating graphs with the data afterwards, here is the code I have.
// Get Rainfall
$rainfall = array();
for($i=1;$i<=$count;$i++)
{
if($data->val($i,2) != 'Rainfall') // Check if not the column title
{
$rainfall[] = $data->val($i,2);
}
}
For your info $data is the excel spreadsheet object and the method $data->val(row,col) is what returns me the value. In this case I am getting data from column 2.
Screenshot of spreadsheet
Did you try an array_push() ?
array_push($rainfall, $data->val($i,2));
I would use a strict comparison with the not identical operator here instead of using the not equals operator:
if($data->val($i,2) !== 'Rainfall')
If $data->val($i,2) is an integer and you use == both sides will be cast to integers which would give you the result that all integers would work as you expect except for zero. Here's a summary of the difference between == and === when comparing the string "RainFall" with zero:
0 == "RainFall" : true
0 != "RainFall" : false
0 === "RainFall" : false
0 !== "RainFall" : true
I think that the array is treating the 0 like false, which could explain it not going into the array. Would something like this work (if you are using integers)?
(int)($data->val($i,2));
or
(float)($data->val($i,2);)
The problem lies in the if statement. You're trying to compare a string with an integer, which according to the PHP documentation will typecast both to integers.
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
You can read more here http://php.net/manual/en/language.operators.comparison.php.
Update: The if statement won't work in the case of 0 because (int)"Rainfall" will by typecasted into 0 by PHP causing the statement to be if (0 != 0) { ... }.
If $i represents the row number, why don't you start from 2 instead of 1?

Categories