1
Dear experienced developers and codar art learners.
I believe it is common in some system you have to check the next item of a array
. For example in this case I am checking if the next one is the same as the previous one:
$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 using the function isset() to check if it is set, this would not help, because sometimes my array can return with empty value.
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. There is a function that checks whether you have this index in the array
? not to blow the bug?
I understand you want to check if the next item is equal to the current one, but what is the expected output? You may have better alternatives to solve this.
– Roberto de Campos
You might give this message after $i reaches the last possible value and $j wants to go further, since its value is $j=$i+1. The highest rate is 10, in your case, but $j wants to go up to 10+1, which doesn’t exist.
– user4701
If you only need to compare an item with the following because it does not simplify and change the
for
for< length - 1
? So you don’t even need the previous one, just compare it directly with the next one, because you know it’s always valid– Isac