for loop reverse a string using php-ThrowExceptions

Exception or error:

I am receiving an error
Uninitialized string offset:

this is my code

$post = "Test"; 
$strtext = strlen($post);

for($i=strlen($post);$i>=0;$i--)
{
    echo $post[$i];
}

I reviewed my code and I think that all are correct, but I don’t think its perfect because it has an error.

result must be tseT without an error.
and I am not allowed to use error_reporting(0);

This is our assignment tbh, reverse the string using 1 for loop only.

Thank you for your answers.

How to solve:

Instead of looping it manually use PHP function strrev

Solution 1:

<?php

$post = "Test";
echo strrev($post);

Output:

tseT

Solution 2:

$post = "Test";

for($x=strlen($post)-1; $x>=0; $x--)
{
    echo $post[$x];
}

Output:

tseT

Answer´╝Ü

Try this:

for($i=strlen($post) - 1; $i>=0; $i--){
    echo $post[$i];
}

as the array index are from 0 to n-1

Leave a Reply

Your email address will not be published. Required fields are marked *