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)*/
I have two PHP variables that can either be empty (i.e. value="") or contain a name in the format Last, First with a comma and a space between the last and first name (e.g. Mouse, Mickey).
I would like to make a simple check here and say if a variable is not empty AND is equal to another then check a checkbox but this doesnt work.
Can someone here show me what I am doing wrong (in the below example the checkbox should be checked) ?
My problem is that the checkbox always gets checked, even if the variables don't match.
Example:
$poc1 = "Mouse, Mickey"; // hard-coded for testing
$poc2 = "Mouse, Mickey"; // hard-coded for testing
<input type="checkbox" id="check2" name="Copy_POC" <?php if(($poc2 != "") && (strcmp($poc2,$poc1))) { echo "checked"; } ?> />
Many thanks for any help with this, Tim.
You need to look at the function signature for strcmp, and its return values:
int strcmp ( string $str1 , string $str2 )
So the function returns an int, but what kind of int? According to the manual:
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
In other words: if both strings are equal, strcmp returns 0, which evaluates to false. What you should've written therefore is:
strcmp($str1, $str2) !== 0
This will evaluate to true if the 2 strings do not match. Of course, you only want to see the ckeckbox checked when the two strings don't match:
if ($str1 != '' && strcmp($str1, $str2) === 0)
{
//checked
}
That ought to do it. Of course, this still relies on your calling functions to check these strings being equal. That doesn't really add up, though, and it might be a lot easier to just write:
if ($str1 && $str1 === $str2)
//an empty string is falsy + type & value check on 2 strings using === operator
Note
As you may already know, PHP is built on C, and therefore has a lot of C-like str* functions. Whenever you see a function like strcmp and strstr, check its return value. Like the C string.h functions, it often returns either a pointer (part of the string where substring is found, like strstr), or an integer (index/offset in string)...
<?php if($poc2 && $poc2 === $poc1) echo "checked" ?>
I am wondering why following statement in PHP is returning true?
true>=4
for example such line will echo 1
echo true>=4;
Can anyone explain me the logic behind this?
4 is also true (because it's non-zero), and true is equal to true, so it's also greater than or equal to true.
If a bool or null is compared to anything other than a string, that thing is cast to a bool. See the docs.
In addition to Davids answer, I thought to add something to give a little more depth.
PHP unlike other programming languages, if your not careful with your operators/syntax you can fall into tricky pot holes like the one you experience.
As David said,
4 is also true (because it's non-zero), and true is equal to true, so
it's also greater than or equal to true.
Take this into account
True is greater than false.
true = 1
false = 0
So take this for example:
$test = 1;
if ($test == true){
echo "This is true";
}else{
echo "This is false";
}
The above will output
This is true
But if you take this:
$test = 1;
if ($test === true){
echo "This is true";
}else{
echo "This is false";
}
The above will output:
This is false
The added equals sign, looks for an exact match, thus looking for the integer 1 instead of PHP reading 1 as true.
I know this is a little off topic, but just wanted to explain some pot holes which PHP contains.
I hope this is some help
Edit:
In response to your question:
echo true>=4;
Reason you are seeing 1 as output, is because true/false is interpreted as numbers (see above)
Regardless if your doing echo true>=4 or just echo true; php puts true as 1 and false as 0
The ever flaky Xdebug is on the fritz at the mo' (normal service will be resumed as soon as possible), so I am reduced to "debug by echo".
echo($path_info['filename'] . ' ' . $licence['issue_timestamp'].'<br>');
if ($path_info['filename'] != $licence['issue_timestamp'])
{
die('They are NOT equal');
$_SESSION['error_messages'][] = 'This licence file has been copied';
return False;
}
else
die('They are equal');
outputs
1319266557_ 1319266557
They are equal
Any idea what I am doing wrong? Is there something special about (trailing) underscores?
The docs state:
$a != $b Not equal TRUE if $a is not equal to $b after type juggling.
And that "type juggling" looks mighty suspicious. Elsewhere on that page, it mentions:
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.
And the example is a dead giveaway as to what's happening in your case:
var_dump(100 == "1e2"); // 100 == 100 -> true
In terms of how strings are converted to integers, that can be seen here. The salient bit is (my bold):
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
The value is given by the initial portion of the string.
Example: $foo = 1 + "10 Small Pigs"; // $foo is integer (11)
That's why "123_" is equal to "123" (a). Bottom line, use !== since that ensures both the value and the type are the same.
(a) See the online PHP executor:
One of the bone-headed things that PHP does is that == only compares values "after type juggling". What this means is that what most sane people think of as == is really === in PHP. Try
$path_info['filename'] !== $licence['issue_timestamp'].
Code will explain more:
$var = 0;
if (!empty($var)){
echo "Its not empty";
} else {
echo "Its empty";
}
The result returns "Its empty". I thought empty() will check if I already set the variable and have value inside. Why it returns "Its empty"??
http://php.net/empty
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Note that this is exactly the same list as for a coercion to Boolean false. empty is simply !isset($var) || !$var. Try isset instead.
I was wondering why nobody suggested the extremely handy Type comparison table. It answers every question about the common functions and compare operators.
A snippet:
Expression | empty($x)
----------------+--------
$x = ""; | true
$x = null | true
var $x; | true
$x is undefined | true
$x = array(); | true
$x = false; | true
$x = true; | false
$x = 1; | false
$x = 42; | false
$x = 0; | true
$x = -1; | false
$x = "1"; | false
$x = "0"; | true
$x = "-1"; | false
$x = "php"; | false
$x = "true"; | false
$x = "false"; | false
Along other cheatsheets, I always keep a hardcopy of this table on my desk in case I'm not sure
In case of numeric values you should use is_numeric function:
$var = 0;
if (is_numeric($var))
{
echo "Its not empty";
}
else
{
echo "Its empty";
}
Use strlen() instead.
I ran onto the same issue using 1/0 as possible values for some variables.
I am using if (strlen($_POST['myValue']) == 0) to test if there is a character or not in my variable.
I was recently caught with my pants down on this one as well. The issue we often deal with is unset variables - say a form element that may or may not have been there, but for many elements, 0 (or the string '0' which would come through the post more accurately, but still would be evaluated as "falsey") is a legitimate value say on a dropdown list.
using empty() first and then strlen() is your best best if you need this as well, as:
if(!empty($var) && strlen($var)){
echo '"$var" is present and has a non-falsey value!';
}
From a linguistic point of view empty has a meaning of without value. Like the others said you'll have to use isset() in order to check if a variable has been defined, which is what you do.
empty() returns true for everything that evaluates to FALSE, it is actually a 'not' (!) in disguise. I think you meant isset()
To accept 0 as a value in variable use isset
Check if variable is empty
$var = 0;
if ($var == '') {
echo "empty";
} else {
echo "not empty";
}
//output is empty
Check if variable is set
$var = 0;
if (isset($var)) {
echo "not empty";
} else {
echo "empty";
}
//output is not empty
It 's working for me!
//
if(isset($_POST['post_var'])&&$_POST['post_var']!==''){
echo $_POST['post_var'];
}
//results:
1 if $_POST['post_var']='1'
0 if $_POST['post_var']='0'
skip if $_POST['post_var']=''
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but
without a value in a class)
From PHP Manual
In your case $var is 0, so empty($var) will return true, you are negating the result before testing it, so the else block will run giving "Its empty" as output.
From manual:
Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string) NULL
FALSE array() (an empty array) var
$var; (a variable declared, but
without a value in a class)
More: http://php.net/manual/en/function.empty.php
You need to use isset() to check whether value is set.
Actually isset just check if the variable sets or not.In this case if you want to check if your variable is really zero or empty you can use this example:
$myVar = '';
if (empty($myVar))
{
echo "Its empty";
}
echo "<br/>";
if ($myVar===0)
{
echo "also zero!";
}
just for notice $myVar==0 act like empty function.
if (empty($var) && $pieces[$var] != '0') {
//do something
}
In my case this code worked.
empty should mean empty .. whatever deceze says.
When I do
$var = '';
$var = '0';
I expect that var_dump(empty($var)); will return false.
if you are checking things in an array you always have to do isset($var) first.
use only ($_POST['input_field_name'])!=0 instead of !($_POST['input_field_name'])==0 then 0 is not treated as empty.
Not sure if there are still people looking for an explanation and a solution. The comments above say it all on the differences between TRUE / FALSE / 1 / 0.
I would just like to bring my 2 cents for the way to display the actual value.
BOOLEAN
If you're working with a Boolean datatype, you're looking for a TRUE vs. FALSE result; if you store it in MySQL, it will be stored as 1 resp. 0 (if I'm not mistaking, this is the same in your server's memory).
So to display the the value in PHP, you need to check if it is true (1) or false (0) and display whatever you want: "TRUE" or "FALSE" or possibly "1" or "0".
Attention, everything bigger (or different) than 0 will also be considered as TRUE in PHP. E.g.: 2, "abc", etc. will all return TRUE.
BIT, TINYINT
If you're working with a number datatype, the way it is stored is the same.
To display the value, you need to tell PHP to handle it as a number. The easiest way I found is to multiply it by 1.
proper example. just create int type field( example mobile number) in the database and submit an blank value for the following database through a form or just insert using SQL. what it will be saved in database 0 because it is int type and cannot be saved as blank or null. therefore it is empty but it will be saved as 0. so when you fetch data through PHP and check for the empty values. it is very useful and logically correct.
0.00, 0.000, 0.0000 .... 0.0...0 is also empty and the above example can also be used for storing different type of values in database like float, double, decimal( decimal have different variants like 0.000 and so on.