Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading