str_replace & Fatal error: Only variables can be passed by reference

If you’re using a simple str_replace() call in PHP and getting a strange Fatal error that doesn’t make a whole lot of sense to you I have a hunch as to why.

Fatal example:

$file_name = str_replace('findit', 'replaceit', $haystack, 1);

In PHP 5.0.5 some changes were made to how PHP handles variables, functions, and references.  This broke a lot of older code but also introduced some vague and questionable fatal errors.  They meant well by doing this by essentially requiring parameters be passed via reference.  I’m assuming this was to prevent PHP from copying large pieces of data to work on them and thus helping memory performance overall. Luckily there is a simple fix, just declare your variable to be passed inline.

Working example:

$file_name = str_replace('findit', 'replaceit', $haystack, $count = 1);

Note: if you’re working with a large data set in a loop I would highly recommend setting the reference outside of the loop and avoid this inline method.