2

I have an array like this:

Array(a,b,c,a,b)

Now, if I would like to check how many instances of "b" I can find in the array, how would I proceed?

0

4 Answers 4

5

See the documentation for array_count_values(). It seems to be what you are looking for.

$array = array('a', 'b', 'c', 'a', 'b');
$counts = array_count_values($array);
printf("Number of 'b's: %d\n", $counts['b']);
var_dump($counts);

Output:

Number of 'b's: 2

array(3) {
["a"]=> int(2)
["b"]=> int(2)
["c"]=> int(1) }

Sign up to request clarification or add additional context in comments.

Comments

2

Use array_count_values($arr). This returns an associative array with each value in $arr as a key and that value's frequency in $arr as the value. Example:

$arr = array(1, 2, 3, 4, 2);
$counts = array_count_values($arr);
$count_of_2 = $counts[2];

Comments

1

You can count the number of instances by using this function..

 $b = array(a,b,c,a,b);

 function count_repeat($subj, $array) {
    for($i=0;$i<count($array);$i++) {
       if($array[$i] == $subj) {
           $same[] = $array[$i]; //what this line does is put the same characters in the $same[] array.
        }
    return count($same);
 }

echo count_repeat('b', $b); // will return the value 2

Comments

0

Although there are some fancy ways, a programmer should be able to solve this problem using very basic programming operators.
It is absolutely necessary to know how to use loops and conditions.

$count = 0;
$letters= array("a","b","c","a","b"); 
foreach ($letters as $char){
  if ($char == "b") $count = $count+1;
}
echo $count.' "b" found';

NOT a rocket science.

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.