PHP:当使用带有null或空字符串的strpos()时,如何避免警告



我从数据库中提取数据,有时返回的值是空字符串或null。当我尝试评估返回值中是否存在一组字符时,它会生成一个警告。我想知道如何在不生成警告的情况下进行评估,从而降低PHP的速度。我在做什么:

if(strpos($db_result, $valueToCheckFor) !== false) // do stuff

$db_result的值通常为空或null,因为那里什么都没有,这很好,因为我想向它写入数据。偶尔,数据会存在,我想将CONCAT写入数据,但前提是valueToCheckFor不存在。例如:

valueToCheckFor = 'AP'
db_result = ''          <--- yep.  want to write to this (very common - generates Warning)
db_result = 'fnork'     <--- yep.  want to write to this (less common)
db_result = 'fnorkAP'   <--- nope.  do NOT want to write to this (rare)

所以我不关心检查是否工作,因为它工作得很好。我AM担心每次我得到一个空字符串(或null(时,它都会发出警告,比如:

Deprecated: strpos(): Non-string needles will be interpreted as strings in the future.
Use an explicit chr() call to preserve the current behavior

我研究了chr(),但无法理解它是如何应用于此的。

如何修改我的if语句以避免收到这些警告?

通过将$valueToCheckFor强制转换为字符串,这解决了问题:

if(strpos($db_result, (string) $valueToCheckFor) !== false) // do stuff

最新更新