18

I am getting this error on line 57: $password = str_replace($key, $value, $password, 1);

As far as I can tell, I am only passing in variables. Here is some more context:

$replace_count = 0;
foreach($replacables as $key => $value)
{
    if($replace_count >= 2)
        break;
    if(strpos($password, $key) !== false)
    {
        $password = str_replace($key, $value, $password, 1);
        $replace_count++;
    }

}
Edward Yu
  • 776
  • 2
  • 6
  • 15
  • `str_replace` can take array .. you don't need to loop – Baba Jun 24 '13 at 15:52
  • 1
    From the manual: "If passed, this will be set to the number of replacements performed". This means the function updates the value of the forth parameters. You have to just specify the variable name as a reference. – user1402647 Jun 24 '13 at 16:16
  • 1
    possible duplicate of [PHP: "... variables can be passed by reference" in str\_replace()?](http://stackoverflow.com/questions/5842366/php-variables-can-be-passed-by-reference-in-str-replace) – T.Todua Nov 19 '14 at 20:10

2 Answers2

13

You can't pass a constant of 1, a fix is to set it to a variable as so.

Change:

$password = str_replace($key, $value, $password, 1);

to:

$var = 1
$password = str_replace($key, $value, $password, $var);

UPDATE: Changed to declare variable outside of the method call from feedback in comments.

immulatin
  • 2,118
  • 1
  • 12
  • 13
  • `str_replace($key, $value, $password, $var = 1);` also incorrect, use `str_replace($key, $value, $password, $var);`. otherwise you will get `Strict Standards: Only variables should be passed by reference in......` – bystwn22 Jun 24 '13 at 16:45
  • @bystwn22 Thanks, I don't have those settings locally so never would've seen this error. I updated the answer – immulatin Jun 24 '13 at 16:50
11

Passing 1 there makes no sense. (Why not pass 42, or -5?) The 4th parameter of str_replace is only used to pass information back to you. The function does not use the original value of the variable at all. So what would be the point (even if allowed) of passing something in, if it is not used, and you are not going to use the new value sent back to you? That parameter is optional; just don't pass anything at all.

newacct
  • 119,665
  • 29
  • 163
  • 224
  • 4
    Exactly, this is a common error to believe that the 4th argument is to set the number of replacement. As the doc says: `count: If passed, this will be set to the number of replacements performed.` – Erdal G. Nov 02 '14 at 17:05
  • 1
    in case you read that a few times and, like me, still didn't connect the dots - performed = _after_ the replacement has taken place, so the **resulting** count (you'd need a different way of restricting the amount of times needle is replaced in haystack) – Sandra Aug 17 '22 at 13:36