0

I need to count how many times a user entered word appears in an array. The user enters text into a form textbox, and that text goes to a String variable in php, which is then exploded into an array with an index for every space.

I need to count how many times each word appears. Let's say the text is "yo yo yo man man man", then I need to count how many times the word "yo" appears as well as the amount of times "man" appears. Please keep in mind this text could be anything the user enters, so using a method such "str_word_count" isn't option, since it only takes hard-coded text.

The code I have set up so 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>

    The text you entered was:

    <?php

        $text = $_POST['text']; // get text
        $textToCount = explode(' ', $text);
        echo $text.'<br><br>';

        for($i=0; $i<count($textToCount); $i++)
        {   

        }



    ?>

</body>

1 Answer 1

2

Use array_count_values():

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

In a foreach loop:

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

Just keep in mind that punctuation may throw this off so if punctuation is allowed be sure to remove it before using your code.

Always check the manual as PHP has a ton of built in functions for arrays. Demo

Sign up to request clarification or add additional context in comments.

9 Comments

I've seen this as well. The problem I have with this method is that it allows me to print out how many times that word appear, sure, but not in the format that I wanted. I should have included that in the original post. The format I was looking for is: yo appears 3 times man appears 3 times etc...
You do realize you can get this to appear in any format you want. This is just an array.
Right, but for the format I'm trying, I get duplicates. It prints "yo appears 3 times", 3 times.
Then you need to fix your loop. Looping through this should be trivial.
There might be something I don't understand or am missing about associate arrays then.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.