Advertisement
Stann

most-frequent-tag

Aug 15th, 2014
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.46 KB | None | 0 0
  1. <!--Write a PHP script MostFrequentTag.php which generates an HTML input text field and a submit button. In the text field the user must enter different tags, separated by a comma and a space (", "). When the information is submitted, the script should generate a list of the tags, sorted by frequency. Then you must print: "Most Frequent Tag is: [most frequent tag]". Semantic HTML is required. Styling is not required.-->
  2.  
  3. <!doctype html>
  4. <html lang="en">
  5. <head>
  6.     <meta charset="UTF-8">
  7.     <title>Most Frequent Tag</title>
  8. </head>
  9. <body>
  10. <p>Enter Tags:</p>
  11.  
  12. <form action="" method="get">
  13.     <input type="text" name="tags" autofocus/>
  14.     <input type="submit"/><br/><br/>
  15. </form>
  16.  
  17. <?php
  18. if ($_GET) {
  19.     if ($_GET['tags'] != '') {
  20.         //split the string
  21.         $tags = explode(', ', $_GET['tags']);
  22.  
  23.         //find all keys and their frequency
  24.         $occurrences = array_count_values($tags);
  25.        
  26.         // reversed sort of the array with keys keeping
  27.         arsort($occurrences);
  28.         foreach ($occurrences as $key => $value) {
  29.             echo "$key : $value times" . '<br>';
  30.         }
  31.         echo '<br>';
  32.  
  33.         //return all keys as value
  34.         $keys = array_keys($occurrences);
  35.         //check if all values are equal
  36.         if (count(array_unique($occurrences)) == 1) {
  37.             echo 'No Most Frequent Tag exist';
  38.         } else {
  39.             echo "Most Frequent Tag is: $keys[0]";
  40.         }
  41.     }
  42. }
  43. ?>
  44.  
  45. </body>
  46. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement