The problem here is that strpos() returns the starting position index of $str1 in $str2 (if found), otherwise it returns false. So in this example, strpos() returns 0 (which is then coerced to false when referenced in the if statement). That’s why the code doesn’t work properly.
The correct solution would be to explicitly compare the value returned by strpos() to false as follows:
$str1 = 'yabadabadoo'; $str2 = 'yaba'; if (strpos($str1,$str2) !== false) { echo """ . $str1 . "" contains "" . $str2 . """; } else { echo """ . $str1 . "" does not contain "" . $str2 . """; }
Note that we used the !== operator, not just the != operator. If we use !=, we’ll be back to the problem that 0 is coerced to false when referenced in a boolean expression, so 0 != false will evaluate to false.
If you want to explore more about PHP, visit our videos section! Below are some examples:
You can also follow some of the broadcasters who program in PHP, as below:
Another cool way to find out interesting things about PHP is to access our project page!
In 2024 we're witnessing a critical point in democratic technology: the integration of blockchain and…
We’re thrilled to announce an exciting opportunity for you to win not one but two…
Acquiring practical skills is crucial for career advancement and personal growth. Education Ecosystem stands out…
Artificial Intelligence (AI) has been making significant strides in various industries, and the software development…
Another week to bring you the top yield platforms for three of the most prominent…
If you hold a large volume of LEDU tokens above 1 million units and wish…
View Comments
strpos($str1,$str2) !== 1
or
strpos($str1,$str2) == 0
Nice!
I always forget to declare stuff like this....
Tricky one!