Skip to content

Instantly share code, notes, and snippets.

@AliAlmasi
Last active October 24, 2024 21:45
Show Gist options
  • Save AliAlmasi/ba94ec9ff0495b25606d1f7f7662bf57 to your computer and use it in GitHub Desktop.
Save AliAlmasi/ba94ec9ff0495b25606d1f7f7662bf57 to your computer and use it in GitHub Desktop.
Reverse a string in JS & PHP using this `str_reverse()` function
const readline = require("node:readline");
const input = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const str_reverse = (string) => {
let reverse = "";
for (let index = string.length; index > 0; index--)
reverse += string[index - 1];
return reverse;
};
input.question(`\nEnter any string: `, (string) => {
console.log(
`\n=========\nInput: '${string}'\nOutput: '${str_reverse(string)}'\n`
);
input.close();
});
<?php
$input = readline("Enter a string: ");
echo "\n";
function str_reverse($string)
{
$output = "";
$cnt = 0;
for($i = strlen($string); $i > 0; $i--)
$output[$cnt++] = $string[$i - 1];
return $output;
}
echo "input: '$input'\n";
echo "output: '" . str_reverse($input) . "'\n";
// TEST: $ php str_reverse.php
// Enter a string: alialmasi
//
// input: 'alialmasi'
// output: 'isamlaila'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment