FizzBuzz with input from user


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <h2>Enter in 3 numbers</h2>
  2. <p>First 2 is the one you want to check for multiples, 3rd is the number you want to count from 1 to</p>
  3. <form action="fizzbuzz.php" method="post">
  4. <p>Insert number A <input type="number" name="A" size="5" maxlength="10" value="<?php if (isset($_POST['A'])) echo $_POST['A']; ?>" />(required)</p>
  5. <p>Insert number B<input type="number" name="B" size="5" maxlength="10" value="<?php if (isset($_POST['B'])) echo $_POST['B']; ?>" />(required)</p>
  6. <p>Insert number N <input type="number" name="N" size="5" maxlength="10" value="<?php if (isset($_POST['N'])) echo $_POST['N']; ?>" /> (required)</p>
  7. <p><input type="submit" name="submit" value="Print the series!" /></p>
  8. <input type="hidden" name="submitted" value="TRUE" />
  9. </form>
  10.  
  11. <?php
  12.  
  13. $page_title = 'Fizz Buzz';
  14.  
  15. // Check if the form has been submitted.
  16. if (isset($_POST['submitted'])) {
  17.  
  18. if (is_numeric($_POST['A']) && is_numeric($_POST['B']) && is_numeric($_POST['N']) ) {
  19.  
  20. // Print the heading.
  21. echo '<h1 id="mainhead">This is how it should be</h1>';
  22.  
  23. $i = NULL; // Initialize $i.
  24.  
  25. for ($i=1; $i <=$_POST['N']; $i++)
  26. {
  27.  
  28. if ( $i%$_POST['A']==0 && $i%$_POST['B'] !== 0 ){echo "F ";}
  29. elseif ( $i%$_POST['B']==0 && $i%$_POST['A'] !== 0 ) {echo "B ";}
  30. elseif ( $i%$_POST['A']==0 && $i%$_POST['B'] == 0 ) {echo "FB ";}
  31. else {echo "$i ";}
  32. }
  33.  
  34. // Print some spacing.
  35. echo '<p><br /></p>';
  36.  
  37. } else { // Invalid submitted values.
  38. echo '<h1 id="mainhead">Error!</h1>
  39. <p class="error">Please enter a valid #</p><p><br /></p>';
  40. }
  41.  
  42. } // End of main isset() IF.
  43.  
  44. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.