Jump to content

Array Nuances


mjohnson025

Recommended Posts

Hi everyone. I am doing some studying for the Zend certification. I came across this question:

'What will the following script output?'

<?php
$array = array(1, 2, 3, 5, 8, 13, 21, 34, 55);

$sum = 0;

for ($i = 0; $i<5; $i++){
  $sum += $array[$array[$i]];
}

echo "<br/>". $sum;


?>

 

The answer is 78, and the explanation was less than helpful for me, as I struggled to understand what they were saying. Can anyone here put it into simpler terms? Here is their explanation: 'If you step through the code manually, you'll find that , when $i is zero, then  $array[$array[$i]] becomes  $array[$array[0]], or $arrray[1], that is 2.'

 

I think I get it, sort of, but if someone could give a better explanation I would be much appreciative.

 

Thanks,

Mike

Link to comment
https://forums.phpfreaks.com/topic/242206-array-nuances/
Share on other sites

New Sum: 2 | Amount Added: 2 | Array Index: 1 | Index: 0

New Sum: 5 | Amount Added: 3 | Array Index: 2 | Index: 1

New Sum: 10 | Amount Added: 5 | Array Index: 3 | Index: 2

New Sum: 23 | Amount Added: 13 | Array Index: 5 | Index: 3

New Sum: 78 | Amount Added: 55 | Array Index: 8 | Index: 4

 

78

 

<?php
$array = array(1, 2, 3, 5, 8, 13, 21, 34, 55);

$sum = 0;

for ($i = 0; $i<5; $i++){
  $sum += $array[$array[$i]];
  echo "New Sum: {$sum} | Amount Added: {$array[$array[$i]]} | Array Index: {$array[$i]} | Index: {$i}<br />";
}

echo "<br/>". $sum;


?>

Link to comment
https://forums.phpfreaks.com/topic/242206-array-nuances/#findComment-1243834
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.