-2

I have this array

 $arr=   [
      0 => "T"
      1 => "h"
      2 => "e"
      3 => " "
      4 => "w"
      5 => "r"
      6 => "i"
      7 => "t"
      8 => "e"
      9 => "r"
      10 => ""
      11 => " "
      12 => "w"
      13 => "a"
      14 => "s"
      15 => " "
    ..
    ..

for($j=0;$j<count($arr);$j++)
{  
    if($arr[$j-1]==" ")
    {

    }
}

In this if condition if($arr[$j-1]==" ") getting this error

message: "Undefined offset: -1", exception: "ErrorException

the previous key exists but i'm still getting error

Any solution to fix this issue

user3653474
  • 3,393
  • 6
  • 49
  • 135

2 Answers2

1
 $arr=   [
      0 => "T"
      1 => "h"
      2 => "e"
      3 => " "
      4 => "w"
      5 => "r"
      6 => "i"
      7 => "t"
      8 => "e"
      9 => "r"
      10 => ""
      11 => " "
      12 => "w"
      13 => "a"
      14 => "s"
      15 => " "
    ..
    ..

for($j=0;$j<count($arr);$j++)
{  
    if($j > 0 && $arr[$j-1]==" ")
    {

    }
}
tzztson
  • 328
  • 3
  • 22
0

Index Starts at zero

You are trying to check if the previous key is a space, do something to current key!

$j Is starting form zero. so you are checking the index $j-1.

To achieve what you want, you should start form 1 to count($arr) it self.

Try code below:

for($j = 1; $j < count($arr); $j++)
{  
    if($arr[$j - 1] == " ")
    {
       // do something here
    }
}

Or this:

for($j = 0; $j < count($arr) - 1; $j++)
{  
    if($arr[$j] == " ")
    {
       $next = $arr[$j+1];
       // do something here
    }
}

Or Even this:

for($j = 0; $j < count($arr); $j++)
{  
    if(isset($arr[$j]) && $arr[$j - 1] == " ")
    {
       // do something here
    }
}
Alijvhr
  • 1,695
  • 1
  • 3
  • 22