Dejan Toteff
Dejan Toteff

Reputation: 2207

Missing last string character when looping in PHP

It seems very easy task to echo all elements from a string one by one. I was surprised when this code showed all but the last characters of the string:

function FirstReverse($str) {
    $arr='';
    $len=strlen($str);

    $i=0;
    while($i<$len+1)
    {
        echo $str[$i];
        echo "<hr />";
        $i++;
    }
}

Upvotes: 0

Views: 340

Answers (1)

Ben
Ben

Reputation: 9001

Try:

function FirstReverse($str){
    for($i=0;$i<strlen($str);$i++){
        echo $str[$i].'<hr/>';
    }
}

Why:

for($i=0;$i<strlen($str);$i++)

$i variable is announced and is equal to 0.

The For loop continues until $i<strlen($str) (which works because $i starts on 0, not 1).

At the end of the For function, $i increases by one each time.

 echo $str[$i].'<hr/>';

This was just shorter than having two different echo commands - . joins two PHP strings.

Upvotes: 2

Related Questions