如何在PHP中最好比较为0? [英] How best to compare to 0 in PHP?

查看:73
本文介绍了如何在PHP中最好比较为0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在开发的一段代码中,我需要从数据库中取一个值,并检查它是否 0 。最初,我写成:

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

但是当我今天再看一遍,我发现了一个bug:

  var_dump(foo== 0); // bool(true)

//而我们在这里...
var_dump(intval(foo)); // int(0)

由于这个值来自数据库, / strong>意味着它将是一个字符串,所以我想我可以这样做:

  if($ myVal === 0)

但它似乎是反直觉的,因为我真的想处理一个整数,这似乎表明我们正在处理字符串。 此外,根据字段类型,任何给定的数据库访问器都不会意外地将值转换为适当的类型。



你可以使用什么方法来检查值为0,当它可以是字符串或int?

解决方案

简短版本:

  if($ myVal==='0')

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

长版本:

  if($ myVal === 0 || $ myVal ==='0')
/ pre>

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?

解决方案

Short version:

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

or

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

Long version:

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

这篇关于如何在PHP中最好比较为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆