# array_count_values

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
hello,

here is the code:

<?
\$a=array(1,3,4,5,6,7,8,9,10);
\$b=array_count_values(\$a);
print_r(\$b);
?>

the result will be: [1]=>1 [3]=>1...........

I would like that the keys which doesnt appear in the result of
array_count_values (here it is the number 2)
have the value 0.......the new result will be: [1]=>1 [2]=>0
[3]=>1...........

how can we formulate a php code to resolve that ?

## Re: array_count_values

I think the below works.

Scott

\$a=array(1,3,4,5,6,7,8,9,10);
\$b=array_count_values(\$a);

//sort the key
ksort(\$b);

//document highest key
foreach(\$b as \$key=>\$value)
{
\$counter=\$key;
}

//load elements that do not exist with zeros
for(\$i=\$counter;\$i>=0;\$i--)
{
if(!isset(\$b[\$i]))
{
\$b[\$i]=0;
}
}

//sort by key again
ksort(\$b);
print_r(\$b);

<a> wrote:

## Re: array_count_values

Pedro's is more concise.

Scotty

## Re: array_count_values

Pedro's is more concise.

Scotty

## Re: array_count_values

<a> wrote:

php\$ cat countall.php
<?php
\$a = array(1, 3, 4, 5, 6, 7, 8, 9, 10);
\$b = array_count_values(\$a);

#print_r(\$b);

for (\$i = 0; \$i <= max(\$a); ++\$i) {
if (!isset(\$b[\$i])) \$b[\$i] = 0;
}
ksort(\$b);
print_r(\$b);
?>

php\$ php countall.php
Array
(
[0] => 0
[1] => 1
[2] => 0
[3] => 1
[4] => 1
[5] => 1
[6] => 1
[7] => 1
[8] => 1
[9] => 1
[10] => 1
)

--
Mail to my "From:" address is readable by all at http://www.dodgeit.com /
== ** ## !! ------------------------------------------------ !! ## ** ==
may bypass my spam filter. If it does, I may reply from another address!

## Re: array_count_values

Pedro Graca wrote:

Make that

for (\$i = 1; \$i < max(\$a); ++\$i) {

--
Mail to my "From:" address is readable by all at http://www.dodgeit.com /
== ** ## !! ------------------------------------------------ !! ## ** ==
may bypass my spam filter. If it does, I may reply from another address!

## Re: array_count_values

a wrote:

Like this, for example:

\$a = array(1,3,4,5,6,7,8,9,10);
\$range = range(1,10);
foreach(\$range as \$number) {
if (in_array(\$number, \$a)) {
\$b[\$number] = 1;
} else {
\$b[\$number] = 0;
}
}

JP

--
E-mail adres is <jpk"at"akamail.com>, waarbij "at" = @.

## Re: array_count_values

a wrote:

<?php

\$a = array(1,3,4,5,6,7,8,9,10);
\$b = array_count_values(\$a);
\$c = array_fill(1,10,0);
\$d = array_diff(\$c,\$b);
ksort(\$e = \$b + \$d);
print_r(\$e);

?>

JW

## Re: array_count_values

Tank you for all these answers !