rgomez rgomez - 2 months ago 10
PHP Question

PHP Array check the count of same values

I'm having troubles comparing two arrays with

array_inersect()
, tried lot of suggestion from SO but none worked. So here is my problem:

I have two arrays:

$base_array = array(2,2,2,1);

Array
(
[0] => 2
[1] => 2
[2] => 2
[3] => 1
)


And another one
$risks
that prints like this:

Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 1
[4] => 2
[5] => 8
[6] => 6
)


What I want is to see if the same number and type of values from
$base_array
fits into
$risks
array. Right now it should return false cause I only have two occurences of number 2 and base array has 3. But if I set
$base_array
to:

$base_array = array(2,2,1);


This should return true.

Answer

One approach can be counting occurrence of each number then manually comparing them. For this you need two array to keep the occurrence count.

$base_array_count = [];
$risks_count = [];

In your case $base_array_count will look like

$base_array_count[1] = 1
$base_array_count[2] = 2

And the $risks_array_count will look like

$risks_count[1] = 1
$risks_count[2] = 2
$risks_count[3] = 1
$risks_count[4] = 1
$risks_count[6] = 1
$risks_count[8] = 1

Now loop through $base_array_count and check if each numbers count value is same as in $risks_array_count

Complete code after edit:

$base_array = array(1,2,2,7);
$risks_array = array(2,3,4,5,6,7);

$base_array_count = array();
$risks_array_count = [];

for($i = 0; $i < sizeof($base_array); $i++){
    if( !isset($base_array_count[$base_array[$i]] ))
        $base_array_count[$base_array[$i]] = 0;
    $base_array_count[$base_array[$i]]++;
}

for($i = 0; $i < sizeof($risks_array); $i++){
    if( !isset($risks_array_count[$risks_array[$i]] ))
        $risks_array_count[$risks_array[$i]] = 0;
    $risks_array_count[$risks_array[$i]]++;
}

$same = true;

if (sizeof($base_array) <= sizeof($risks_array)) {
    for ($i = 0; $i < sizeof($base_array); $i++) {
        if(!isset($risks_array_count[$base_array[$i]]) || $base_array_count[$base_array[$i]] != $risks_array_count[$base_array[$i]]){
            $same = false;
            break;
        }
    }
} else {
    $same = false;
}
if($same)
    echo "TRUE";
else
    echo "FALSE";