Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

if ($myVal == 0) { ...

But when I looked at it again today, I realised a bug there:

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:

if ($myVal === "0")

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?

like image 557
nickf Avatar asked May 18 '09 00:05

nickf


People also ask

What is == and === in PHP?

== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. Syntax: operand1 == operand2. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.

Is null Falsy in PHP?

NULL essentially means a variable has no value assigned to it; false is a valid Boolean value, 0 is a valid integer value, and PHP has some fairly ugly conversions between 0 , "0" , "" , and false . Show activity on this post. Null is nothing, False is a bit, and 0 is (probably) 32 bits.

How PHP compare data of different types?

In PHP, variables of different data types can be compared using the loose comparison operator which is two equal signs (==). If two operands of different types are compared using loose comparison then there is an attempt to convert one or both of the operands and then compare them.

How compare two strings in if condition in PHP?

Answer: Use the PHP strcmp() function You can use the PHP strcmp() function to easily compare two strings. This function takes two strings str1 and str2 as parameters. The strcmp() function returns < 0 if str1 is less than str2 ; returns > 0 if str1 is greater than str2 , and 0 if they are equal.


2 Answers

Short version:

if ("$myVal" === '0')

or

if (strval($myVal) === '0')

Long version:

if ($myVal === 0 || $myVal === '0')
like image 94
cletus Avatar answered Oct 12 '22 11:10

cletus


The best I've got currently is this:

is_numeric($myVal) && $myVal == 0
like image 36
nickf Avatar answered Oct 12 '22 11:10

nickf