Cesar Bielich
Cesar Bielich

Reputation: 4945

Count instances of value/key in merged arrays and set value by count

I am looking at trying to do an array_merge with these arrays but I need to be able to count how many times a particular value in the array appears and give me that data back.

Here are the original arrays

Array
(
    [0] => this
    [1] => that
)
Array
(
    [0] => this
    [1] => that
    [2] => some
)
Array
(
    [0] => some
    [1] => hello
)

Ultimately I would like it to look like this

Array
(
    [this] => 2
    [that] => 2
    [some] => 2
    [hello] = > 1
)

That would ultimately allow me to get the key and value I need. I tried 'array_unique` in this process but realized that I may not be able to count the instances of each array that they appear since this would just simple remove them all but one.

I tried something list this

$newArray = array_count_values($mergedArray);

foreach ($newArray as $key => $value) {
    echo "$key - <strong>$value</strong> <br />"; 
}

but I am getting results like this

Array
(
    [this] => 2
    [that] => 2
    [some] => 2
    [hello] = > 1
    [this] => 3
    [that] => 3
    [some] => 3
    [hello] = > 2
    [this] => 2
    [that] => 2
    [some] => 2
    [hello] = > 1
)

Upvotes: 0

Views: 503

Answers (3)

Rasclatt
Rasclatt

Reputation: 12505

Use array_count_values():

$a1 = array(0 => 'this', 1 => 'that');
$a2 = array(0 => 'this', 1 => 'that', 2 => 'some');
$a3 = array(0 => 'some', 1 => 'hello');

// Merge arrays
$test   =   array_merge($a1,$a2,$a3);
// Run native function
$check  =   array_count_values($test);

echo '<pre>';
print_r($check);
echo '</pre>';

Gives you:

Array
(
    [this] => 2
    [that] => 2
    [some] => 2
    [hello] => 1
)

EDIT: As noted by AlpineCoder:


"This will work only in the case of input arrays using numeric (or unique) keys (since array_merge will overwrite values for the same non-integer key)."

Upvotes: 9

rink.attendant.6
rink.attendant.6

Reputation: 46218

As tyteen4a03 mentioned, use nested foreach loops:

$arr1 = array('foo', 'bar');
$arr2 = array('foo', 'bar', 'baz');
$arr3 = array('baz', 'bus');

$result = array();

foreach(array($arr1, $arr2, $arr3) as $arr) {
    foreach ($arr as $value) {
        if (!isset($result[$value])) {
            $result[$value] = 0;
        }
        ++$result[$value];
    }
}

print_r($result);

The outer foreach goes through each set of items (i.e. each array) and the inner foreach loop goes through each item in each set. If the item isn't in the $result array yet, create the key there.

Result:

Array
(
    [foo] => 2
    [bar] => 2
    [baz] => 2
    [bus] => 1
)

Upvotes: 0

AlpineCoder
AlpineCoder

Reputation: 627

$res = array();

foreach ($arrays as $array) {
    foreach ($array as $val) {
        if (isset($res[$val])) {
            $res[$val]++;
        } else {
            $res[$val] = 1;
        }
    }
}

Upvotes: 1

Related Questions