The str_replace call has the correct three arguments: search='world', replace='PHP', subject=$text.
Step 2: Understand string immutability in PHP
str_replace returns a new string; it does not change the original string $text unless assigned back, e.g., $text = str_replace('world', 'PHP', $text);
Final Answer:
str_replace does not modify $text directly -> Option C
Quick Check:
Assign result to variable to update string [OK]
Hint: Assign str_replace result to variable; original string stays same [OK]
Common Mistakes:
Not assigning result back to variable
Assuming str_replace changes string in place
5. You want to replace multiple words in a string at once: replace 'red' with 'blue' and 'green' with 'yellow' in $text. Which code correctly does this in PHP?
hard
A. $result = str_replace(['red', 'green'], ['blue', 'yellow'], $text);
B. $result = str_replace('red', 'blue', $text);
str_replace('green', 'yellow', $text);
C. $result = str_replace('red', 'blue', $text) && str_replace('green', 'yellow', $text);
D. $result = str_replace('red' => 'blue', 'green' => 'yellow', $text);
Solution
Step 1: Understand str_replace with arrays
str_replace accepts arrays for search and replace to perform multiple replacements in one call.
Step 2: Analyze each option
$result = str_replace(['red', 'green'], ['blue', 'yellow'], $text); uses arrays correctly. $result = str_replace('red', 'blue', $text);
str_replace('green', 'yellow', $text); performs first replacement but second call discards result and uses original $text, so 'green' remains. $result = str_replace('red', 'blue', $text) && str_replace('green', 'yellow', $text); uses && which returns boolean, not string. $result = str_replace('red' => 'blue', 'green' => 'yellow', $text); uses invalid syntax.
Final Answer:
$result = str_replace(['red', 'green'], ['blue', 'yellow'], $text); -> Option A
Quick Check:
Use arrays in str_replace for multiple replacements [OK]
Hint: Use arrays in str_replace to replace many words at once [OK]
Common Mistakes:
Using multiple str_replace without chaining
Using logical operators instead of chaining
Wrong syntax for arrays in str_replace
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.