Advertisement
dimipan80

Sum of Digits

Apr 22nd, 2015
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.42 KB | None | 0 0
  1. <!--Write a PHP script SumOfDigits.php which receives a comma-separated list of integers from an input form and creates a two-column table. The first column should contain each of the values from the input. The second column should contain the sum of the digits of each value. If the value is not an integer number, print "I cannot sum that". Styling the page is optional.-->
  2.  
  3. <!DOCTYPE html>
  4. <html>
  5. <head lang="en">
  6.     <meta charset="UTF-8"/>
  7.     <title>Sum Of Digits</title>
  8.     <style type="text/css">
  9.         table, td {
  10.             border: 1px solid #000;
  11.         }
  12.     </style>
  13. </head>
  14. <body>
  15. <form method="post">
  16.     <p>
  17.         <label for="input-text">Input string:</label>
  18.         <input type="text" name="input_text" id="input-text" required/>
  19.         <input type="submit" value="Submit"/>
  20.     </p>
  21. </form>
  22. <table>
  23.     <tbody>
  24.     <?php
  25.     if (!array_key_exists('input_text', $_POST)) {
  26.         die('The Input Form can\'t been Empty!!!');
  27.     }
  28.  
  29.     $numbers = preg_split("/[,\s]+/", $_POST['input_text'], -1, PREG_SPLIT_NO_EMPTY);
  30.     foreach ($numbers as $el) {
  31.         ?>
  32.         <tr>
  33.             <td><?= htmlspecialchars($el) ?></td>
  34.             <td>
  35.                 <?php
  36.                 $result = 'I cannot sum that';
  37.                 if ((intval($el) !== 0 || $el === '0') && (string)((int)$el) === $el) {
  38.                     $count = strlen($el);
  39.                     $result = 0;
  40.                     for ($i = 0; $i < $count; $i++) {
  41.                         $result += (int)$el[$i];
  42.                     }
  43.                 }
  44.  
  45.                 echo $result;
  46.                 ?>
  47.             </td>
  48.         </tr>
  49.     <?php
  50.     }
  51.     ?>
  52.     </tbody>
  53. </table>
  54. </body>
  55. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement