Transform 2 php array into a single array

Asked

Viewed 163 times

1

I have 2 Arrays:

"val" => {
    "0": "2"
    "1": "4"
    "2": "6"
    "3": null
    "4": null
}

"p" => {
    "0": "4"
    "1": "5"
    "2": "7"
    "3": "8"
    "4": "9"
}

Before that I want to take the elements of array val which are 2 4 6 and add in the same 4 5 7.

All in a single array.

  • 2

    array_merge()?

  • 1

    Put the expected result in the question as well, as your solution attempt describing the error you found.

1 answer

3

Good afternoon, let’s start: first you can use the Array_merge to join the 2 arrays, taking the example you gave you have the 2 arrays:

$val = [
    "0" => "2",
    "1" => "4",
    "2" => "6",
    "3" => null,
    "4" => null
];

$p = [
    "0" => "4",
    "1" => "5",
    "2" => "7",
    "3" => "8",
    "4" => "9"
];

Example:

$array_mergido = array_merge($val, $p);

But if you want only unique values without being repeated you can use the Array_unique:

$array_mergido = array_unique(array_merge($val, $p));
  • the principle is the same, $val = array('banana', 'maçã');

$p = array('batata', 'cenoura');

$array_mergido = array_merge($val, $p);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.