Bird
0
0

What is the issue with this PHP code snippet?

medium📝 Debug Q7 of 15
PHP - String Functions
What is the issue with this PHP code snippet?
$text = 'search here';
if (strpos($text, 'search')) {
echo 'Found';
} else {
echo 'Not found';
}
AIt fails to detect 'search' at the start because strpos returns 0 which is treated as false.
BThe function <code>strpos</code> is used incorrectly; it should be <code>strstr</code>.
CThe code will always print 'Not found' because strpos returns false for existing substrings.
DThere is a syntax error in the if statement.
Step-by-Step Solution
Solution:
  1. Step 1: Understand strpos return values

    strpos returns 0 if the substring is found at the start of the string.
  2. Step 2: Evaluate the if condition

    In PHP, 0 is treated as false in boolean context, so the if condition fails even though substring exists.
  3. Step 3: Correct approach

    Use strict comparison: if (strpos($text, 'search') !== false) to correctly detect substring presence.
  4. Final Answer:

    It fails to detect 'search' at the start because strpos returns 0 which is treated as false. -> Option A
  5. Quick Check:

    Remember strpos can return 0, use !== false [OK]
Quick Trick: Check strpos result with !== false to avoid false negatives [OK]
Common Mistakes:
  • Using if (strpos(...)) without strict comparison
  • Confusing strpos with strstr
  • Assuming 0 is true in PHP conditionals

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes