How do I print the triangular series onto a file using PHP?

one text

Solution:

Since I got confirmed that saving to file itself is not an issue, I am posting 3 solutions

$number = intval($_POST['number-entered']); // convert target number to string;
$triangle_numbers = [];

// SOLUTION 0 (no change to your loop, but you should use something else, range(1,1000) is very bad there)
foreach (range(1, 1000) as $i) {
    $triangle_numbers[] = $i * ($i + 1) / 2;
}
$triangle_numbers = array_slice($triangle_numbers,0,$number);

// SOLUTION 1:
foreach ( range(1, $number) as $i ) { //we don't need to go all the way to 1000 if user only wants 5, and if they want 2000 we are covered
$triangle_numbers[] = $i * ( $i + 1 ) / 2;
}


// SOLUTION 2 
for ($i = 1; $i<=$number; $i++) { //it's as above, i just changed the loop
    $triangle_numbers[] = $i * ($i + 1) / 2;
}

// rest is pretty much the same
//edit, i removed weird reopen part. it made you write to the same line over and over
        $contents = fopen('here.txt', "w");
    fwrite($contents, $number . "\n");
    fwrite($contents, implode(', ', $triangle_numbers)); // read https://www.php.net/manual/en/function.implode.php
    fwrite($contents, "\n$number\n");
    fclose($contents);

Source