2

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?

1

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

2 Comments

array_count_values? :O Nice!
this $array is only test i have many value in my $array and i want know count each value in my array
1

simple way:

print_r(array_count_values($array));

if you want just the "ok":

echo array_count_values($array)['ok'] // output 2

Comments

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.