Count number of times a word appears in php array -


i need count how many times user entered word appears in array. user enters text form textbox, , text goes string variable in php, exploded array index every space.

i need count how many times each word appears. let's text "yo yo yo man man man", need count how many times word "yo" appears amount of times "man" appears. please keep in mind text user enters, using method such "str_word_count" isn't option, since takes hard-coded text.

the code have set far:

form.php:

<html>      <head>          <title>part 1</title>      </head>      <body>          <h1></h1>          <form action="part1result.php" method = "post">              <input type="text" name="text"/>             <input type="submit" value="submit" />          </form>      </body>  </html> 

result.php:

<head>      <title></title>  </head>  <body>      text entered was:      <?php          $text = $_post['text']; // text         $texttocount = explode(' ', $text);         echo $text.'<br><br>';          for($i=0; $i<count($texttocount); $i++)         {             }        ?>  </body> 

use array_count_values():

$texttocount = explode(' ', 'yo yo yo man man man'); print_r(array_count_values($texttocount)); //array ( [yo] => 3 [man] => 3 ) 

in foreach loop:

$texttocount = explode(' ', 'yo yo yo man man man'); $words = array_count_values($texttocount); foreach ($words $word => $count) {      printf('%s appears %u times', $word, $count); } 

just keep in mind punctuation may throw off if punctuation allowed sure remove before using code.

always check manual php has ton of built in functions arrays. demo


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -