Bird
0
0

You want to check if the word 'cat' exists anywhere in the string $sentence. Which code snippet correctly does this?

hard📝 Application Q8 of 15
PHP - String Functions
You want to check if the word 'cat' exists anywhere in the string $sentence. Which code snippet correctly does this?
Aif (strpos($sentence, 'cat') !== false) { echo 'Found'; }
Bif (strstr($sentence, 'cat') === true) { echo 'Found'; }
Cif (strpos('cat', $sentence)) { echo 'Found'; }
Dif (strstr($sentence, 'cat') === false) { echo 'Found'; }
Step-by-Step Solution
Solution:
  1. Step 1: Use strpos with strict comparison

    To check existence, use strpos and compare strictly to false to handle position 0 correctly.
  2. Step 2: Evaluate options

    if (strpos($sentence, 'cat') !== false) { echo 'Found'; } uses correct syntax. if (strstr($sentence, 'cat') === true) { echo 'Found'; } compares substring to boolean incorrectly. if (strpos('cat', $sentence)) { echo 'Found'; } reverses parameters. if (strstr($sentence, 'cat') === false) { echo 'Found'; } checks for false incorrectly.
  3. Final Answer:

    if (strpos($sentence, 'cat') !== false) { echo 'Found'; } -> Option A
  4. Quick Check:

    Use strpos !== false to check substring presence [OK]
Quick Trick: Use !== false with strpos to detect substring [OK]
Common Mistakes:
  • Using === true with strstr
  • Swapping strpos parameters
  • Checking strstr === false incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes