PHP: 当使用带有 null 或空字符串的 strpos() 时如何避免警告?
PHP: how can i avoid warnings when using strpos() with null or empty strings?
我正在从数据库中提取数据,有时返回的值是空字符串或 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)
所以我不关心检查 working,因为它工作正常。我 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
我正在从数据库中提取数据,有时返回的值是空字符串或 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)
所以我不关心检查 working,因为它工作正常。我 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