0

so i have a bit difficulty in combining arrays in php. So let say i have these 2 array

array:4 [▼
  20 => "University"
  21 => "Polic Station"
  22 => "Ambulance"
  1  => "Zoo"
]

array:4 [▼
  20 => "abc"
  21 => "def"
  22 => "ghi"
  1  => "jkl"
]

How do i actually combine this to this

array:4 [▼
  20 => "abc University"
  21 => "def Polic Station"
  22 => "ghi Ambulance"
  1  => "jkl Zoo"
]
1

1 Answer 1

5

Here's the result:

$arr = array(
    20=>'University',
    21=>'Polic Station',
    22=>'Ambulance',
    1=>'Zoo');
$arr2= array(
    20=>'abc',
    21=>'def',
    22=>'ghi',
    1=>'jkl');
$arr_out = array();
foreach($arr as $key=>$el) {
    $arr_out[$key] = $arr2[$key] ." ".$el;
}
var_dump($arr_out);

Obviously, you'll need to keep in mind to check whether the key exists in the second array so you do not get an error when accessing the value.

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

1 Comment

Works like charm, i will make validation on second array later. Thanks.

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.