Treat for undefined index in the array

1

Dear experienced developers and apprentices of the art of coding.

I think it's common for some system to have to check the next item for a array . For example in this case I'm checking if the next one is the same as the previous item:

$item_anterior = "";
$array = [0,1,2,3,4,5,6,7,8,9,10];
$ainda_nao_foi = true;

for($i=0;$i<$array.lenght();$i++){   

   if($ainda_nao_foi){   
     echo "<p>O Site do Stack overflow é demais! .$array[$i].</p>";
     $item_anterior = $array[$i];
     $ainda_nao_foi = false;
   }
   //próximo
   $j = $i + 1;

   if($item_anterior != array[$j]){
        $ainda_nao_foi = true;
   }
}

Even though I use the isset () function to check if it's set, this would not help, because sometimes my array may return empty.

The problem is that in this if :

if($item_anterior != array[$j]){
   $ainda_nao_foi = true;
}

The PHP generates a warning warning that the index is not set. Is there a function that checks to see if it has this index in array ? to not break the error?

    
asked by anonymous 16.02.2018 / 13:46

2 answers

2

To check if the key exists even if the value is null , use the array_key_exists() in place of isset() can add this check in the second if.

$item_anterior = "";
$array = [0,1,1,2,3,4,5,6,7,8,9,10, '', null, null];
$ainda_nao_foi = true;

foreach($array as $k => $v){

    if($ainda_nao_foi){
        echo "<p>O Site do Stack overflow é demais! .$array[$k].</p>";
        $item_anterior = $array[$k];
        $ainda_nao_foi = false;
    }

    $j = $k + 1;

    if(array_key_exists($j, $array) && $item_anterior != $array[$j]){
        $ainda_nao_foi = true;
    }
}

A simpler example of the function difference:

$arr = array(1, null, '' , 'teste');

var_dump(isset($arr[1])); //false
var_dump(array_key_exists(1, $arr)); //true

Example - ideone

Related:

What's the difference in checking an array with isset and array_key_exists?

    
16.02.2018 / 14:14
0

I would do the reverse, instead of checking the next one, check the above:

for ($i=0; $i < $array.lenght(); $i++){   
   if(($i == 0) || ($array[$i - 1] != $array[$i])) 
     echo "<p>O Site do Stack overflow é demais! .$array[$i].</p>";
}

But if you want to keep that format, you could add a if :

$item_anterior = "";
$array = [0,1,2,3,4,5,6,7,8,9,10];
$ainda_nao_foi = true;

for($i=0;$i<$array.lenght();$i++){   

   if($ainda_nao_foi){   
     echo "<p>O Site do Stack overflow é demais! .$array[$i].</p>";
     $item_anterior = $array[$i];
     $ainda_nao_foi = false;
   }
   //próximo
   $j = $i + 1;

   if(($j < $array.lenght()) && ($item_anterior != array[$j])){
        $ainda_nao_foi = true;
   }
}
    
16.02.2018 / 14:07