phparrays

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
)

Solution

  • 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)."