Notification texts go here Contact Us Buy Now!

What's my mistake with "strpos" function?

The strpos function in PHP returns false if the specified substring is not found in the string being searched, which can be misinterpreted as 0 in a type-unspecific conditional statement.

To accurately check if the substring exists, it's essential to use the strict equality operator (===) when comparing the result of strpos with false. This ensures that the comparison is made based on both the value and the type of the variables being compared.

Consider the following example:

if (strpos($string, 'test') === false) {
  $change = $string2;
  break;
} 

In this code, the condition strpos($string, 'test') === false is used to check if the substring "test" is not present in the $string variable. If the substring is not found, it sets the $change variable to the value of $string2. The break statement is used to exit the loop early.

Using the strict equality operator (===) ensures that the comparison is made accurately, and the code will only execute the if block if the substring is not present in the string.

Another way to achieve the same result is to use the ternary operator:

$change = (strpos($string, 'test') === false) ? $string2 : $change;

In this code, the ternary operator is used to set the value of $change based on the result of the strpos function. If the substring is not found (i.e., strpos($string, 'test') === false), it sets $change to the value of $string2; otherwise, it leaves the value of $change unchanged.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.