PHP: "... variables can be passed by reference" in str_replace()?

Dexter picture Dexter · Apr 30, 2011 · Viewed 14.2k times · Source

I created a function to print a prepared-statement-sql-string with the variables in it, based on what I found in this other StackOverflow question.

Here is my code:

foreach($params as $idx => $param) {
    if ($idx == 0) continue;
    $sql = str_replace('?', "'" . $param . "'", $sql, 1);
}
printError($sql);

When I run this I get: Fatal error: Only variables can be passed by reference for line 3. However when i use

$sql = preg_replace('/\?/', "'" . $param . "'", $sql, 1);

for line 3 it works fine.

Any idea why?

Answer

VoteyDisciple picture VoteyDisciple · Apr 30, 2011

The very last parameter, count, is passed by reference. You can see this in the description at http://us.php.net/str_replace where there's a & in front of the variable.

This means you cannot use a literal 1 there. You'd have to do:

$sql = str_replace('?', "'" . $param . "'", $sql, $count);
echo $count;

You'll now have displayed on the screen how many instances were replaced.