DEV Community

Discussion on: Reverse a string: awful answers only

Collapse
 
_garybell profile image
Gary Bell • Edited
function reverseString(string $input): string
{
    $reverseCode = '';
    for ($i = strlen($input) -1; $i >= 0; $i--) {
        //$reverseCode .= 'substr("' . str_replace("'", "\'", $input) . '", ' . $i . ', 1) . ';
        $reverseCode .= 'substr(\"' . $input . '\", ' . $i . ', 1) . ';
    }
    $reverseCode .= '\"\";';
    $reversedString = exec("php -r \"echo $reverseCode\"");
    return $reversedString;
}
Enter fullscreen mode Exit fullscreen mode

Ok, so this monstrosity uses the built-in substr method. But instead of using that to determine the string, it builds a whole bund of PHP code to execute within the shell, calls that via exec, and returns the string.

Awfully bad practice, inefficient, and dangerous. It's the type of code which gives PHP a bad name!