Mohamed Omer
Mohamed Omer

Reputation: 11

passing by reference won't work in php

i was about to make a filter helper and to just test my idea by basic replacing function using passing by reference and it won't work!

<?php
$text ="hello world i am here !";

 function findandreplace(&$text, $search, $replaced)
 {

    return str_replace($search, $replaced, $text);

 }

print findandreplace($text,'e','E');
print "<br>";
print $text;

the output is always like that :

hEllo world i am hErE !
hello world i am here !

i tried may things but i won't work, so what is my fault.

Upvotes: 0

Views: 80

Answers (1)

Steve
Steve

Reputation: 20469

You are not making any changes to the passed $text string, since str_replace does not modify the passed in string - it receives a copy of the passed in value, and returns the result. It If you assign the result of str_replace to the $text variable, it will work as expected:

 $text ="hello world i am here !";

 function findandreplace(&$text, $search, $replaced)
 {

    $text =  str_replace($search, $replaced, $text); //<-- now it will work
    return $text;

 }

print findandreplace($text,'e','E');
print "<br>";
print $text;

Upvotes: 4

Related Questions