0

I have the following array()

$statoA = array();

It has

Italy
France
France
Italy
Spain

I know I can use array_count_values($statoA)

But how to do a foreach to have:

<ul>
  <li>2 France</li>
  <ll>2 Italy</li>
  <li>1 Spain</li>
</ul>
1
  • just use the results from array_count_values($statoA) in the foreach loop Commented Apr 13, 2017 at 3:44

2 Answers 2

1
foreach(array_count_values($statoA) as $k=>$v){
    echo '<li>'.$v.' '.$k.'</li>';
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you are using array_count_values(), then you will have a array where the keys are the terms from your original array, and the values are the counts for each term. You can then loop through this array to build your markup:

<ul>
    <?php
        foreach (array_count_values($statoA) as $key => $value) {
            //$key is now the term (France, Italy, Spain)
            //$value is now the frequency or counts of the term
            echo "<li>{$value} {$key}</li>";
        }
    ?>
</ul>

Documentation for array_count_values is available here: http://php.net/manual/en/function.array-count-values.php

Documentation on foreach is available here: http://php.net/manual/en/control-structures.foreach.php

5 Comments

@thanks a lot, this helped me more than the other answer but since it is basically the same and the other answer came first I had to accept the previous. Said that, thanks a lot because I've learned due to your explanation :)
No worries, happy to be of service
PHP has a code style standard that is opt-in, but highly recommended, maintained by the PHP-FIG group. In the code style standard, PSR-2, all control structures use braces and are never placed on a single line, for readability and consistency (php-fig.org/psr/psr-2/#control-structures). Section 5.6 of the standard is specifically for the foreach control structure, and states it should look as it does in my answer (php-fig.org/psr/psr-2/#foreach). I always try to answer within the standard to keep things, well...standardized.
im not talking about the foreach, but {$value} and {$key}
That's for two considerations, mainly - readability, and consistency across all data types. I find it easier, personally, to pick the variables out, and my IDE will color hint as well. For consistency, it's handy when you want to do something like echo "Name: {$user->name}.". I find that more agreeable than than dot-concatenation (again, personally). Eventually I just got in the habit of doing it regardless of the data type in the variable. If there are no variables to interpret in the string, I also go so far as to specifically use apostrophes instead of quotes. Just marks intent well.

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.