n.am n.am - 6 months ago 12
PHP Question

How can I increment the value of only one index in the array using PHP

$vaccinesArr=array("0","0","0","0","0","0","0","0","0","0","0");
for($i = 0; $i < 11 ; $i++){
while($row = mysqli_fetch_assoc($result)){
if ($row['vaccID']== $i){
$vaccineArr[$i]++;
}
}
}


This is the part of my code, I need to increment according to this condition but I keep on getting syntax error, I searched but all the results I find are using foreach and incrementing all the indexes of the array while here I want to increment only one specific index. Can anyone help?

Answer

Your code will only work on the first iteration of the for loop, because when the inner while loop finishes there won't be any more rows to fetch from the query. You could rewind the query, but a better way to do it would be without the for loop.

while ($row = mysqli_fetch_assoc($result)) {
    $vaccinesArr[$row['vaccID']]++;
}

Also, if the elements of $vaccinesArr are supposed to be numbers, you shouldn't put them in quotes. PHP will convert the strings to numbers when you use ++, but why be confusing?

$vaccinesArr = array(0, 0, 0, ....);