Question

I've got a feeling this is a silly/stupid mistake on my part, but I need a new set of eyes... I'm trying to loop through a string using substr but am not getting what's expected.

For example, echo substr("950122", 2, 2); outputs 01 to the screen instead of 5. And using an index of 3 gives me 122 instead of 0.

How would I loop through the string correctly?
http://ideone.com/YKz7g3

<?php
$str = "950122";
for( $i = 1; $i <= strlen( $str ); $i++ ) {
    echo substr( $str, $i, $i ) . "\n";
}
?>
Was it helpful?

Solution

The start position begins at 0 not 1. So to get 5 you use 1,1 and to get 0 use 2,1.

0,1 will give you the first character 9.

Also, the third parameter to substr() is the length, so if you use 1 you get 1 character from the start or 2 gives you 2 characters from the start.

0,6 will give 950122.

OTHER TIPS

1) i should be 0

2) it should be substr( $str, $i, 1 ) not substr( $str, $i, $i )

http://ideone.com/9qlwje

<?php
$str = "970122";
for( $i = 0; $i <= strlen( $str ); $i++ ) {
    echo substr( $str, $i, 1 ) . "\n";
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top