Recall & Review
beginner
What does the
strpos function do in PHP?It finds the position of the first occurrence of a substring in a string. If the substring is found, it returns the index (starting at 0). If not found, it returns
false.Click to reveal answer
beginner
What is the difference between
strpos and strstr?strpos returns the position (number) of the substring in the string. strstr returns the part of the string starting from the first occurrence of the substring to the end.Click to reveal answer
beginner
What does
strstr return if the substring is not found?It returns
false if the substring is not found in the string.Click to reveal answer
intermediate
How does
strpos handle the case when the substring is at the very start of the string?It returns 0 because the substring starts at the first character (index 0). Remember, 0 is a valid position, not
false.Click to reveal answer
intermediate
How can you safely check if a substring exists using
strpos?Use the strict comparison operator
!== false because strpos can return 0 (which is falsey). For example: if (strpos($text, 'word') !== false) { /* found */ }Click to reveal answer
What does
strpos('hello world', 'world') return?✗ Incorrect
The substring 'world' starts at index 6 in 'hello world'.
What will
strstr('hello world', 'world') return?✗ Incorrect
strstr returns the part of the string starting from the first occurrence of the substring to the end, so it returns 'world'.What does
strpos('apple', 'a') return?✗ Incorrect
The substring 'a' is at the start of 'apple', so the position is 0.
If
strpos returns 0, what does that mean?✗ Incorrect
0 means the substring is found at the very start of the string.
Which is the correct way to check if 'cat' is in a string
$text?✗ Incorrect
Use strict comparison !== false to correctly detect substring presence, even if at position 0.
Explain how
strpos works and how to correctly check if a substring exists in a string.Think about what happens if the substring is at the start.
You got /4 concepts.
Describe the behavior of
strstr and what it returns when the substring is found or not found.It returns a string, not a number.
You got /3 concepts.