Reputation: 519
I looked a question in php related with array. But the question is in array of array. The output of the question is "78". But I don't know how it is work. Please explain it...
<?php
$arr= array(1,2,3,5,8,13,21,34,55);
$sum = 0;
for($i=0; $i<5; $i++)
{
$sum += $arr[$arr[$i]];
}
echo$sum;
?>
Upvotes: 1
Views: 71
Reputation: 1619
I changed some variable names and spaced actions out for clarity, and added a lot of comments. I hope this helps clarify what's happening inside the for loop :).
<?php
/**
* Think of this as [0 => 1, 1 => 2, ...8 => 55,] or more abstractly as
* [index => value, index => value] where Array indices
* start at 0 and climb by every additional value.
*/
$arrayVariable = [1,2,3,5,8,13,21,34,55,];
$sumOfArrayParts = 0;
/* Use for loop to create a bounded iteration (in this case run 5 times) */
for ($arrayIndex = 0; $arrayIndex < 5; $arrayIndex++) {
/**
* Separating this into a separate step for clarity,
* set the index to whatever number is at the index given by $arrayIndex
*/
$chosenIndex = $arrayVariable[$arrayIndex];
/* Index Values: 1, 2, 3, 5, 8 */
$chosenNumber = $arrayVariable[$chosenIndex];
/* Number Values: 2, 3, 5, 13, 55 */
/* Add current value at array index */
$sumOfArrayParts += $chosenNumber;
/**
* Iteration values:
* 1) 0 + 2 // $sumOfArrayParts = 2
* 2) 2 + 3 // $sumOfArrayParts = 5
* 3) 5 + 5 // $sumOfArrayParts = 10
* 4) 10 + 13 // $sumOfArrayParts = 23
* 5) 23 + 55 // $sumOfArrayParts = 78
*/
}
echo $sumOfArrayParts;
?>
Upvotes: 2
Reputation: 8297
It is adding the element at index $arr[$i]
, which is not the same as the element at $i
.
╔═════════════╦════╦═══════════════════╦══════════════╦══════╗
║ Iteration ║ $i ║ $index = $arr[$i] ║ $arr[$index] ║ $sum ║
╠═════════════╬════╬═══════════════════╬══════════════╬══════╣
║ before loop ║ - ║ - ║ - ║ 0 ║
║ 1 ║ 0 ║ 1 ║ 2 ║ 2 ║
║ 2 ║ 1 ║ 2 ║ 3 ║ 5 ║
║ 3 ║ 2 ║ 3 ║ 5 ║ 10 ║
║ 4 ║ 3 ║ 5 ║ 13 ║ 23 ║
║ 5 ║ 4 ║ 8 ║ 55 ║ 78 ║
╚═════════════╩════╩═══════════════════╩══════════════╩══════╝
You can see this illustrated in this phpfiddle example.
Upvotes: 4