Skip to content
Advertisement

PHP make array element 1.5 bigger than previous one

I have a code below. It needs to make array element 1.5 bigger than previous one. Expected outcome should be … 1, 1.5, 2.25, 3.375.. and so on but i get error (undefined offset)

$array= array();  
for($i = 1; $i <= 10; $i++){
$array[$i] = $array[$i] * 1.5;
}


echo "<pre>";
print_r($array);
echo "</pre>";

But it doesn’t seem to work. What my code should look like.

Advertisement

Answer

Your array is empty to start with, so $array[$i] * 1.5 will not work. Initialize your array with at least one number to start with. Use $array[$i-1] for the previous element

<?php

$array= array(1);

for($i = 1; $i <= 9; $i++){
    $array[$i] = $array[$i-1] * 1.5;
}

print_r($array);

will output:

Array
(
    [0] => 1
    [1] => 1.5
    [2] => 2.25
    [3] => 3.375
    [4] => 5.0625
    [5] => 7.59375
    [6] => 11.390625
    [7] => 17.0859375
    [8] => 25.62890625
    [9] => 38.443359375
)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement