0

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
nikko
  • 109
  • 1
  • 11
  • Might not be the most elegant or efficient solution, but how about sorting the array, then iterating over it and checking the current element against the previous one and holding counters in a mapping? – JussiV Apr 09 '18 at 05:53
  • i want to get not only the number of duplicate string, but also the string itself, ex. dog x2 – nikko Apr 09 '18 at 05:57
  • @nikko Number of duplicates or occurrences? – 4EACH Apr 09 '18 at 06:00

4 Answers4

2

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";
}
Saad Suri
  • 1,352
  • 1
  • 14
  • 26
1

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 />";
}
1

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>';
}
Rahul
  • 1,617
  • 1
  • 9
  • 18
0
<?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>';
}
?>
sunny bhadania
  • 423
  • 3
  • 5