Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can echo in php array count each value

Tags:

arrays

php

how can echo count of each value in php array? for example in this array:

 $array = array(test,test,ok,test,ok); 

now how can echo count test or ok in this array?

like image 805
saber Avatar asked Sep 18 '26 06:09

saber


1 Answers

Example straight from the official PHP.net

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

If you want to echo then throw that command in.

For your example:

<?php
    $array = array(test,test,ok,test,ok); 
    print_r(array_count_values($array));
?>

The output is:

Array
(
    [test] => 3
    [ok] => 2
)

To echo try a foreach loop or something like this:

echo "Test = ".array_count_values($array)['test'];

The output is:

Test = 3
like image 158
les Avatar answered Sep 19 '26 20:09

les



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!