I have an array that contains values with the same string, how will I able to count those same string into a number.
example array:
$animals = array('dog','dog','cat','mouse','cat');
output:
dog x2,
cat x2,
mouse x1
I have an array that contains values with the same string, how will I able to count those same string into a number.
example array:
$animals = array('dog','dog','cat','mouse','cat');
output:
dog x2,
cat x2,
mouse x1
Use array_count_values
$animals = array('dog','dog','cat','mouse','cat');
$count_values = array_count_values($animals);
print_r($count_values );
Output
Array
(
[dog] => 2
[cat] => 2
[mouse] => 1
)
And Iterate it over like this
foreach($occurences as $key => $item){
echo $key ." x" .$item .",";
print "\n";
}
This would do:
// The verbose way
<?php
$counts = [];
$animals = array('dog','dog','cat','mouse','cat');
foreach ($animals as $value) {
if (key_exists($value, $counts)) {
$counts[$value] += 1;
} else {
$counts[$value] = 1;
}
}
?>
...but php has a method that does exactly that
<?php
$counts = array_count_values($animals);
?>
and later, if you want to print the occurences
foreach ($counts as $key => $value) {
echo $key." x".$value."<br />";
}
you need to use foreach()
with array_count_values()
like this
$animals = array('dog','dog','cat','mouse','cat');
$values=array_count_values($animals) ;
foreach ($values as $key=>$value) {
echo $key ."X". $value;
echo '<br>';
}
<?php
$array = array('dog','dog','cat','mouse','cat');
$vals = array_count_values($array);
// print_r($vals);
foreach ($vals as $key=>$value) {
echo $key ." X". $value;
echo '<br>';
}
?>