-4

error message when trying to print the next position in loop?

$coba = "testing"; 
for($h=1;$h<(count($coba));$h++){
    echo $coba[$h+1];
}                
Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61

3 Answers3

0

If this is your code, you would get that error:

$coba = "testing"; 
for($h=1;$h<strlen($coba);$h++){
    echo $coba[$h+1];
}

The reason is you're trying to print something that don't exist.

Vindicated
  • 21
  • 2
0

You are incrementing $h to a number greater than the array. That's why you are getting the offset error.

Rob David
  • 11
  • 2
  • 1
0

Original code is incorrect here --> for($h=1;$h<(**count**($coba));$h++){

See the PHP reference guide for difference in count() and strlen().

count($coba) is 1

strlen($coba) is 7

If you use strlen then the code would correctly loop through the string:

$coba = "testing"; 
for($h=1;$h<strlen($coba);$h++){
    echo $coba[$h+1];
}

Now, regarding the error you mentioned, when I run the above I get:

PHP Notice: Uninitialized string offset: ...

Two problems here with your original code. Since I do not know your original intent, I can only guess at what you were trying to do with the loop.

Problem #1: indexing into the string should start with 0, not 1

Problem #2: $coba[$h+1] will be an invalid index at the END of the array at h+1.

You can either adjust the indexing h+1 to just be h OR change the loop to loop 1 less via for($h=0;$h<(strlen($coba)-1);$h++){

Thus, final code could look like:

$coba = "testing";
for($h=0;$h<(strlen($coba)-1);$h++){
    echo $coba[$h+1];
}

Which outputs when run:

esting

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
ChuckB
  • 522
  • 4
  • 10