0

I want to count the number of a group array in the array. Example

$arr1 = [61,41,41,61,89,90]
$arr2 = [61,41]
$result = 2    //found 61,41 in $arr1  2 time;

Or Example

$arr1 = [89,61,41,41,61,90]
$arr2 = [61,41,89]
$result = 1    //found 61,41,89 in $arr1  1 time;

How to write the code, or concept?

3
  • The second example you provided does not make any sense. Could you elaborate a bit more? Commented Feb 16, 2015 at 8:51
  • I would have expeceted the second result to be 3 Commented Feb 16, 2015 at 8:53
  • 1
    What if, 1 value appears once and the other appears 3 times would the result be 4? Commented Feb 16, 2015 at 8:56

2 Answers 2

1

I hope this will help you..

$arr1 = array(61,41,41,61,89,90);
$arr2 = array(61,41);

$count = array_count_values($arr1); //count values from arr1

$result = array();
foreach($arr2 as $row) {
    $result[$row] = array_key_exists($row, $count) ? $count[$row] : 0;
}

echo min($result);

$arr2 = [61,41] output: 2

$arr2 = [61,41,89] output: 1

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

Comments

1
$arr1 = array(61,41,41,61,89,90);
$arr2 = array(61,41);

$occurrences = min(
    array_count_values(array_intersect($arr1, $arr2)) + array_fill_keys($arr2, 0)
);

Arguably a somewhat obscure solution, but a single expression. Returns the number that the entire $arr2 set occurs in $arr1.

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.