PHP function Exercises: Reverse a string

PHP function: Exercise-3 with Solution

Write a function to reverse a string.

Pictorial Presentation:

PHP function Exercises: Reverse a string

Sample Salution:

PHP Code:

function reverse_string($str1)
 $n = strlen($str1);
 if($n == 1)
    return $str1;
   return reverse_string(substr($str1,1, $n)) . substr($str1, 0, 1);

Sample Output:


Flowchart :

Flowchart: Reverse a string

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a function to check a number is prime or not.
Next: Write a function to sort an array.

What is the difficulty level of this exercise?

PHP: Tips of the Day

SQL injection that gets around mysql_real_escape_string()

Consider the following query:

$iId = mysql_real_escape_string("1 OR 1=1");    
$sSql = "SELECT * FROM table WHERE id = $iId";

mysql_real_escape_string() will not protect you against this. The fact that you use single quotes (' ') around your variables inside your query is what protects you against this. The following is also an option:

$iId = (int)"1 OR 1=1";
$sSql = "SELECT * FROM table WHERE id = $iId";

Ref : https://bit.ly/32q3bJ7