Bird
0
0

Why does str_replace() return the modified string instead of changing the original string variable directly?

hard📝 Conceptual Q10 of 15
PHP - String Functions
Why does str_replace() return the modified string instead of changing the original string variable directly?
ABecause strings in PHP are immutable and functions return new strings
BBecause str_replace() modifies the original string by reference
CBecause PHP does not support string replacement
DBecause str_replace() only works on arrays
Step-by-Step Solution
Solution:
  1. Step 1: Understand PHP string behavior

    Strings in PHP are immutable, meaning they cannot be changed after creation.
  2. Step 2: Explain function return behavior

    Functions like str_replace() return a new string with replacements; original string stays unchanged unless reassigned.
  3. Final Answer:

    Because strings in PHP are immutable and functions return new strings -> Option A
  4. Quick Check:

    Immutable strings = return new string [OK]
Quick Trick: Assign str_replace() result to variable to keep changes [OK]
Common Mistakes:
  • Expecting in-place string change
  • Thinking str_replace() modifies by reference
  • Confusing string and array behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes