4

When I use str_replace with an array as second argument like in the much upvoted and accepted answer to this question, I get an array to string conversion notice. Why? Example:

$str = 'a b a ba a';
$numerals = range(1, 10);
$str = str_replace('a', $numerals, $str);

gives :

PHP Notice: Array to string conversion in php shell code on line 1

and the following output:

Array b Array bArray Array

instead of

1 b 2 b3 4

Community
  • 1
  • 1
greg0ire
  • 22,714
  • 16
  • 72
  • 101
  • Because `numerals` is an array. Have you looked at the result of `str`? – Explosion Pills Feb 18 '12 at 22:13
  • That's the problem, the answer says it is supposed to work with an array (and the php documentation too). I added the output to my question. – greg0ire Feb 18 '12 at 22:16
  • 1
    That answer is simply wrong... – VolkerK Feb 18 '12 at 22:37
  • @VolkerK : That's what I'm beginning to think... it seems that sometimes, stack overflow does not work... Downvoted the answer. – greg0ire Feb 18 '12 at 22:39
  • You can take a look at the history of /ext/standard/string.c at http://svn.php.net/viewvc/php/php-src/trunk/ext/standard/string.c?view=log . The relevant part (beginning with `if (Z_TYPE_PP(search) != IS_ARRAY)`) has been there for ages, the suggested solution never worked. – VolkerK Feb 18 '12 at 22:48

1 Answers1

8

You are trying to replace one character ('a') with multiple characters (1,2,3,4,5,6,7,8,9,10). PHP can't figure that out and tries to convert this array to string. When you're using string as $search parameter you must also use string as $replace parameter. An array as $replace parameter can be used only when $search is also an array. Quoting from documentation:

If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.

Here's the code that will work:

$str = 'a b a ba a';
$count = 1;
while(($letter_pos = strpos($str, 'a')) !== false) {
    $str = substr_replace($str, $count++, $letter_pos, 1);
}
Furgas
  • 2,729
  • 1
  • 18
  • 27