0

i'm pulling data from a db and sometimes the value returned is an empty string or null. when i try to evaluate in general for the presence of a set of chars in the returned value, it generates a warning. i'd like to know how to evaluate without generating a warning and thus slowing down PHP. here's what i'm doing:

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

the value of $db_result is often empty or null because there's nothing there, which is fine because i want to write data to it. occasionally, data will exist and i'll want to CONCAT to the data, but only if the valueToCheckFor isn't there. for example:

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)

so i'm not concerned about the check working, because it works fine. i AM concerned that everytime i get an empty string (or null) it cranks out a warning, like this:

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

i looked into chr() but cannot fathom how it applies to this.

how do i modify my if statment to avoid getting these warnings?

3
  • 1
    Don't run the strpos() check if the string is empty? Surround it with an if() to eliminate the possibility. I'm never sure whether you can add in a check for empty() like this: if (!empty($db_result) && strpos($db_result, $value) !== false) { or whether it'll evaluate the right-hand one even if the left is not true.
    – droopsnoot
    Apr 29, 2020 at 12:23
  • It's not the value of $db_result which is producing this warning, it's the value of $valueToCheckFor. If that is an integer, you will get the warning you are seeing. $db_result being '' or even null will not generate it.
    – Nick
    Apr 29, 2020 at 12:48
  • ah! ok! yes, the value of valueToCheck is sometimes just a number. so i guess i should just cast it to a string?
    – WhiteRau
    Apr 29, 2020 at 12:54

1 Answer 1

0

by casting the $valueToCheckFor to a string, this solved the problem:

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.