substr_replace() has the following signature: substr_replace( array <https://www.php.net/manual/en/language.types.array.php>|string <https://www.php.net/manual/en/language.types.string.php> $string, array <https://www.php.net/manual/en/language.types.array.php>|string <https://www.php.net/manual/en/language.types.string.php> $replace, array <https://www.php.net/manual/en/language.types.array.php>|int <https://www.php.net/manual/en/language.types.integer.php> $offset, array <https://www.php.net/manual/en/language.types.array.php>|int <https://www.php.net/manual/en/language.types.integer.php>|null <https://www.php.net/manual/en/language.types.null.php> $length = null <https://www.php.net/manual/en/reserved.constants.php#constant.null> ): string <https://www.php.net/manual/en/language.types.string.php>|array <https://www.php.net/manual/en/language.types.array.php>
Was it deliberate to not allow a null value as the third parameter? If permitted to amend this signature, I think it would be sensible to set null as the default value for $offset and adopt the same logic as the $length parameter. I have recently stumbled upon what I assume is a code smell in multiple SO scripts that use: $prefixed = preg_filter('/^/', 'prefix_', $array); It smells because regardless of the passed in array values' types, there will always be a starting position of each values which are coerced to strings. In other words, the destructive feature of preg_filter() is never utilized. This means that for this task, preg_filter() can be unconditionally replaced with preg_replace(). $prefixed = preg_replace('/^/', 'prefix_', $array); But wait, regex isn't even needed for this task. It can be coded more efficiently as: $prefixed = substr_replace($array, 'prefix_', 0, 0) Next, my mind shifted to suffixing/postfixing. By using $ in the pattern. $prefixed = preg_replace('/$/', 'prefix_', $array); However, there isn't a convenient way to append a string to each value using substr_replace() with the current signature. If the $offset parameter worked like the $length parameter, then the language would provide a native, non-regex tool for appending a static string to all array elements. $suffixed = substr_replace($array, '_suffix'); Finally, I wish to flag the observation that null values inside of an array are happily coerced to strings inside of the aforementioned functions, but null is not consumable if singularly passed in. Some examples for context: https://3v4l.org/ENVip I look forward to hearing feedback/concerns. Mick mickmackusa