Skip to content
Advertisement

PHP behaving strange in for loop with associative array

the attached image is self-explanatory. I think its not new, but i’d like to understand the details behind it. So to summarize my problem, when an associative array, that has only string keys, is passed to a basic for loop, it overflows, when i assign a value to one of its – previously non existant – indexed keys. Why is that? (The image if from tehplayground php sandbox, but does the same on local machine @ PHP 7.3.2 PHP sandbox run img

$result = array('key' => 'value1',
                'key2' => 'value2' );     

echo "size of result=".count($result);
for ($i = 0; $i < count($result); $i++) {
  echo "i=".$i.", result[".$i."]=".$result[$i]."n";
  $result[$i] = "e";
}

//output:
i=0, result[0]=
i=1, result[1]=
i=2, result[2]=
i=3, result[3]=
i=4, result[4]=
i=5, result[5]=
i=6, result[6]=
i=7, result[7]=
i=8, result[8]=
i=9, result[9]=
i=10, result[10]=
i=11, result[11]=
// The printout continues infinitely...

Advertisement

Answer

do like this if you want to run loop based on before everything count:

$result_count = count($result);
for ($i =0; $i<$result_count; $i++){
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement