0

The code works fine but im getting the below error:

Notice: Uninitialized string offset: 3 in /Applications/XAMPP/xamppfiles/htdocs/kwame.php on line 8

Can someone explain why this is so. Thank you.

<?

$string ='Lt4';
$getl = strlen($string);

for($i=0; $i<=$getl; $i++){

echo $string[$i];
}

?>
2
  • 2
    It should be $i<$getl and not $i<=$getl. Commented Dec 20, 2014 at 7:32
  • Character 'L' in your string represents index 0 and the character '4' represents index 2, but your for loop goes up to index 3. Commented Dec 20, 2014 at 7:36

2 Answers 2

3

Because the string doesn't have so many indexes! The index starts with 0. Just change <= to < Like this:

<?php

    $string = "Lt4";
             //^^^-Index 2
             //||-Index 1
             //|-Index 0

    $getl = strlen($string);  //Length: 3

    for($i = 0; $i < $getl; $i++) {  //i -> 0, 1, 2 
        echo $string[$i];  //L, t, 4            
    }

?>

Iteration Overview:

                  Variables            Condition                 Output 

              |  $i  |  $getl    |    $i < $getl  = ?     |    $string[$i] 
-----------------------------------------------------------------------------
Start:        |  0   |    3      |     
Iteration  1: |  0   |    3      |     0 < 3      = TRUE  |         L (Index 0)
Iteration  2: |  1   |    3      |     1 < 3      = TRUE  |         t (Index 1)
Iteration  3: |  2   |    3      |     2 < 3      = TRUE  |         4 (Index 2)
Iteration  4: |  3   |    3      |     3 < 3      = FALSE |      [OFFSET]
              |      |           |                        |
End           |  3   |    3      |                        |
              |      |           |                        |

Output:

Lt4
Sign up to request clarification or add additional context in comments.

Comments

1
<?php
$string ='Lt4';
$getl = strlen($string);
for($i=0; $i<$getl; $i++){
echo $string[$i];
}
?>

enter image description here

index always start from 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.