Jump to content

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


joshgom

Recommended Posts

What im trying to do is create a file with the name "triangular_10.txt" where the number in the file name is the number the user entered. From there I want the text file to have the triangular series of numbers. So if the user enters 10, it'll display the first 10 numbers of the triangular series. So far the file name change is working.

The algorithm is here that I used for PHP:http://www.codecodex.com/wiki/Calculate_a_triangle_number

eg . user enters 10. Result in txt file is first 10 numbers in the triangular series = [1, 3, 6, 10, 15, 21, 28, 36, 45]

This is what I have so far but Im not having any luck! At the moment its only writing the number I entered on to the txt file and nothing else! Any ideas?

$number = $_POST['number-entered'];


    foreach ( range(1, 1000) as $i ) {  
    $triangle_numbers[] = $i * ( $i + 1 ) / 2;  

 } 
    //make a file
    $contents = fopen('gs://a1-task22020.appspot.com/triangular_' .$number. ".txt", "w");
    fwrite($contents, $number);

    //open the file

    $contents = fopen('gs://a1-task22020.appspot.com/' . $contents, 'w');

    // re-open the document if you put something in it
    fwrite($contents, $number);

    fclose($contents);


}
}

 

Link to comment
Share on other sites

5 hours ago, joshgom said:

At the moment its only writing the number I entered on to the txt file and nothing else!

Yes, it's infuriating when it does what you tell it to do and not what you want it to do

fwrite($contents, $number);
                    ^
                    ^
                 number entered

If you want N numbers when the user enter N, why are you always looping from 1 to 1000?

Why two file opens?

Link to comment
Share on other sites

On 6/19/2020 at 9:46 PM, Barand said:

Yes, it's infuriating when it does what you tell it to do and not what you want it to do


fwrite($contents, $number);
                    ^
                    ^
                 number entered

If you want N numbers when the user enter N, why are you always looping from 1 to 1000?

Why two file opens?

Thank you, it worked! 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.