0

I have an array like this:

Array
(
    [0] = Charcoal
    [1] = Natural Gas
    [2] = Combo
)
Array
(
    [0] = Charcoal
    [1] = Propane
    [2] = Combo
)
Array
(
    [0] = Charcoal
    [1] = Propane
    [2] = Natural Gas
    [3] = Combo
)
Array
(
    [0] = Natural Gas
)
Array
(
    [0] = Natural Gas
    [1] = Propane
)
Array
(
    [0] = Propane
)
Array
(
    [0] = 660 sq. inches
)
Array
(
    [0] = 740 sq. inches
)
Array
(
    [0] = 761 sq. inches
)
Array
(
    [0] = 788 sq. inches
)
Array
(
    [0] = 792 sq. inches
)

my desire is for it to look like this:

Array
(
    [0] = Charcoal
    [1] = Propane
    [2] = Natural Gas
    [3] = Combo
    [4] = 660 sq. inches
    [5] = 740 sq. inches
    [6] = 761 sq. inches
    [7] = 788 sq. inches
    [8] = 792 sq. inches
)

I've just recentely learned how to use arrays. So I tried array Merge.. that didnt work.

2
  • Potential repeat question, check this out: stackoverflow.com/questions/1141566/… Commented Apr 12, 2014 at 21:59
  • Create a new array, iterate through all your arrays and for each of their values if doesn't exist in the new array then add it. Commented Apr 12, 2014 at 22:00

2 Answers 2

3

You can do it with call_user_func_array() on array_merge():

$result = call_user_func_array('array_merge', $data);

So your though is correct, but you need a bit tricker way to call it (because you need to pass your array as parameters to array_merge())

Also, note, that merging is done without unique check on values. Thus, if you want to get rid of duplicates, apply array_uniqie():

$result = array_unique(call_user_func_array('array_merge', $data));

Check the fiddle.

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

Comments

2

What you are looking for is to combine all your elements into one array, but only keep each unique element once. Since you have an array of arrays, you need to call array_merge() with each sub-array as a parameter. You can do this using call_user_func_array():

$merged = call_user_func_array('array_merge', $myArray);

Then use array_unique() to keep each element only once:

$merged = array_unique(call_user_func_array('array_merge', $myArray));

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.