skip to Main Content

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

2

Answers


  1. 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
        }
    }
    
    Login or Signup to reply.
  2.  $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]==" ")
        {
    
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search