Php if equals zero

PHP considers null is equal to zero

In PHP, ($myvariable==0) When $myvariable is zero, the value of the expression is true; when $myvariable is null, the value of this expression is also true. How can I exclude the second case? I mean I want the expression to be true only when $myvariable is zero. Of course I can write

($myvariable != null && $myvariable == 0) 

11 Answers 11

You hint at a deep question: when should an expression be true?

Below, I will explain why what you are doing isn’t working and how to fix it.

In many languages null , 0 , and the empty string ( «» ) all evaluate to false, this can make if statements quite succinct and intuitive, but null , 0 , and «» are also all of different types. How should they be compared?

This page tells us that if we have two variables being compared, then the variables are converted as follows (exiting the table at the first match)

Type of First Type of Second Then null/string string Convert NULL to "", numerical/lexical comparison bool/null anything Convert to bool, FALSE < TRUE 

So you are comparing a null versus a number. Therefore, both the null and the number are converted to boolean. This page tells us that in such a conversion both null and 0 are considered FALSE .

Your expression now reads, false==false , which, of course, is true.

Читайте также:  padding

This page provides a list of PHP's comparison operators.

Example Name Result $a == $b Equal TRUE if $a equals $b after type juggling. $a === $b Identical TRUE if $a equals $b, AND they are of the same type. $a != $b Not equal TRUE if $a not equals $b after type juggling. $a <> $b Not equal TRUE if $a not equals $b after type juggling. $a !== $b Not identical TRUE if $a not equals $b, or they are not of the same type. $a < $b Less than TRUE if $a is strictly less than $b. $a >$b Greater than TRUE if $a is strictly greater than $b. $a = $b Greater than/equal TRUE if $a is greater than or equal to $b. 

The first comparator is the comparison you are using now. Note that it performs the conversions I mentioned earlier.

Using the second comparator will fix your problem. Since a null and a number are not of the same type, the === comparison will return false, rather than performing type conversion as the == operator would.

Источник

checking if condition for 0 value

when $_GET['q']=0 if send me in else part. But i want to go in if . if $_GET['q'] have any value even for 0 if should print ok any help pls ?

That should not be the case. Among "set" variables only null values count as "not set", 0 should definitely "be set". Try a var_dump($_GET['q']) .

aside form the typos you have here (which arent the problem cause they would give you syntax errors) that should work. Are you sure that $_GET['q'] is actually 0 . its not in $_POST or passed as $_GET['Q'] ?

4 Answers 4

This is what isset does. Try:

You will get true. If you think isset() returns false on 0 you are looking at the wrong place, look for a bug elsewhere.

You might need something like this considering the value you want is integer

if(isset($_GET['q']) && intval($_GET['q']) > 0 ) < echo "ok"; >else

perhaps array_key_exists() would be more appropriate.

if ( array_key_exists( 'q', $_GET ) ) .

A $_GET value can only be "not set" at all or have a value other than null . As such, using array_key_exists and isset should yield identical results.

Not sure precisely what you mean in the first sentence. But I did a quick test and as far as I can tell, you are correct in the second sentence. I think op may have some weird stuff going on (or an error) as @prodigitalson suggests.

First sentence: foo.php? → $_GET['q'] is not set, foo.php?q → $_GET['q'] === '' . The value is either not set, or has some value. It can never be null . As such, isset and array_key_exists make no difference.

Источник

How best to compare to 0 in PHP?

In one bit of code I'm working on, I need to pull a value from the database and check if it is 0 . Originally, I had written this as:

var_dump("foo" == 0); // bool(true) // and while we're here. var_dump(intval("foo")); // int(0) 

Since this value is coming from the database, that usually means it will be a string, so I suppose I could do this:

but it seems counter-intuitive since I actually want to be dealing with an integer, and this would appear to show that we're working with strings. (I hope that makes sense to you.) Also, it shouldn't be unexpected that any given DB accessor would cast values to their appropriate type, given the field type. What method do you use to check for a value of 0 when it could be a string or an int?

7 Answers 7

My guess is that the long version is actually the faster version. === is a fast comparison because it does no type conversions.

I've just done some benchmarking: in terms of running time, your strval() method is pretty much equal to the is_numeric function I proposed (0.31s to do 100,000 iterations). However, using the "$myVal" === 0 method is about 6-7 times faster, and the long version is over 10 times faster!

I'm honestly surprised that "$myVal" is way slower than strval(). I would've expected it to be the other way around. Interesting results.

The best I've got currently is this:

is_numeric($myVal) && $myVal == 0 

This condition will always return false, since as you said in your question, values from db are returned as strings. $myVal is a string, and the comparison will stop here. You should cast your value to an integer before to do the comparison.

Actually bgy, is_numeric() will return true for a string of a numeric value. See au2.php.net/is_numeric

If the values you get back from the database are strings, but the original datatype is integer, then you probably want your DAO (Data Access Object, or whatever it is that's pulling the data) to cast things to data types you expect. That way, the PHP code that's looking at the values is looking at the data type it expects.

The trouble is, of course, that there isn't a 1-1 correspondence between the data types the DB defines, and the data types PHP defines. However, for the most part this isn't a problem, since there's equivalent types for most of the types we use normally: int, float, bool, string.

The upshot is, that between the place where you query the database, and the place where you check those values, those values should be cast to the data types you expect. I just tested with mysql_fetch_object() on a MySQL table containing an int(10) and a varchar(50); both fields always were pulled in as type "string" by PHP. So if you want one of the fields treated as an int, cast it to an int before you do anything with it. For example:

$rs = mysql_query("SELECT * FROM table"); while ($row = mysql_fetch_object($rs)) < $RealRow->id = (int)$row->id; $RealRow->name = $row->name; // etc. > // . later . if ($RealRow->status == 0) < // do something >

The query and RealRow stuff should be inside a class/method, so that it's encapsulated; that way, ANY part of your code that gets data from table will always get the $RealRow object instead, which will have everything set to the proper data types. Of course, if you change your data types, this requires manually editing the DAO to deal with the casting; it would also be possible to query the DB to get the type of each field (with a "SHOW COLUMNS FROM table"), and automatically cast the fields to the proper data type.

Источник

PHP compare equality, empty string, "0" and 0

I learned that the empty string "", 0 and "0" all mean false in php. I wonder does php take that into account when it comes to comparing equality.

 $str = ""; echo ($str == "0") ? "yes" : "no"; // prints "no" (A) echo ($str == 0) ? "yes" : "no"; // prints "yes" (B) 

Line A suggests that php is comparing $str and "0" as if they are all strings, ignoring that they both can mean false. But line B is comparing their "false" interpretation. So is it the case that php firstly checks if the two values have the same type, if so it checks equality assuming the same type; if not, it uses the boolean meanings of the values (is there type casting involved?)

In the first case you are comparing two strings. So naturally "" is different then "0". On the second one there is more typecasting happening because of the different data types. Use triple equal === and you don't have to worry about the ambiguity of typecasting

If you are interested in many more of those interesting PHP behaviors, I suggest the all-time classic here.

3 Answers 3

I learned that the empty string "", 0 and "0" all mean false in php.

This statement is false. Empty string, 0 and "0" are false when casted to boolean type. Otherwise they are either empty string, integer zero or string with one character, respectively.

== checks values of two variables. If their types are different, some casting happens and unpredictable (for rookies) results come up.

=== checks values of two variables and their types.

Anyway, when you compare "0" == "" , PHP interpreter compares two strings which are different. But when you go with 0 == "" it first changes numeric string to integer. Empty string equals 0. So we end up with 0 == 0 which is true.

Note: "8abc" becomes 8 after casting to integer. abc8 becomes 0 when casted

Источник

Оцените статью