str_replace() Enforces Strings In Array Argument¶
str_replace() accepts an array of strings as third argument: it applies all the replacements to all the strings in that arguments.
Until PHP 8.0, it was possible to pass an array of arrays, and the inner arrays would be omitted in the replacement. In PHP 8.0, the inner arrays are cast to a string, aka Array and then, the replacements occurs.
This is also applicable to str_ireplace().
PHP code¶
<?php
var_dump(str_replace('a', 'b', [[]]));
class x {
function __toString() {
return 'def';
}
}
var_dump(str_replace('a', 'b', [new x]));
?>
Before¶
array(1) {
[0]=>
array(0) {
}
}
array(1) {
[0]=>
object(x)#1 (0) {
}
}
After¶
PHP Warning: Array to string conversion
Warning: Array to string conversion
array(1) {
[0]=>
string(5) Arrby
}
array(1) {
[0]=>
string(3) def
}
PHP version change¶
This behavior changed in 8.0