reverse php string and array

Reverse in PHP

Reverse a string by PHP function strrev

echo strrev("Hello world!");

Result: !dlrow olleH

Reverse words in string

$input_string = 'Hello world! Please reverse my words!';
echo implode(' ', array_reverse(explode(' ', $input_string)));

Result: words! my reverse Please world! Hello

Reverse array items by PHP function array_reverse

$input_array = array(3 , 1, "zero", true);
$reversed_array = array_reverse($input_array);
print_R($reversed_array);

Result: Array ( [0] => 1 [1] => zero [2] => 1 [3] => 3 )

Reverse array items without using any functions

$reversed_array = array();
$input_array = array('zero', 'test', 2, 5, 'here', true);
for ($i=count($input_array)-1;$i>=0;$i--)
{
    $reversed_array[$i] = $input_array[$i];
}
print_R($reversed_array);

Result: Array ( [5] => 1 [4] => here [3] => 5 [2] => 2 [1] => test [0] => zero )

Reverse a string without using any functions

function reverse_string($input_string) {
    $i = 0; $reverted_string = '';
    while ( $input_string[$i] ) {
        $i++;
    }
    $i--;
    while ( $input_string[$i] ) {
        $reverted_string .= $input_string[$i];
        $i--;
    }
    return $reverted_string;
}
$input_string = 'Hello world! Please reverse my words!';
echo reverse_string($input_string);

Result: !sdrow ym esrever esaelP !dlrow olleH