Patrioticcow
Patrioticcow

Reputation: 27048

how to combine a array into itself?

If I do print_r($pieces); I get:

Array
(
    [0] => Albany, NY
)
Array
(
    [0] => Albany, NY
    [1] => Albuquerque, NM
    [2] => Atlanta, GA
    [3] => Augusta, ME
    [4] => Billings, MT
    [5] => Baltimore, MD
)
Array
(
    [0] => Albany, NY
    [1] => Albuquerque, NM
    [2] => Atlanta, GA
    [3] => Augusta, ME
    [4] => Billings, MT
    [5] => Birmingham, AL
    [6] => Boise, ID
    [7] => Boston, MA
    [8] => Buffalo, NY
    [9] => Charleston, SC
    [10] => Charleston, WV
)
.....

What I need to do is to combine this arrays to get unique values. First I need to split it in multiple arrays and then use array_combine, but it doesn't seem to work.

Upvotes: 2

Views: 4484

Answers (2)

Aberel
Aberel

Reputation: 162

Bouni's comment has the best answer:

array_unique(array_reduce($pieces, 'array_merge', []));

Upvotes: 0

deceze
deceze

Reputation: 522135

$unique = array();
foreach ($pieces as $piece) {
    $unique = array_merge($unique, $piece);
}
$unique = array_unique($unique);

Or, if you're using PHP 5.3+:

array_unique(array_reduce($pieces, function ($a, $p) { return array_merge($a, $p); }, array()));

Upvotes: 6

Related Questions