Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I found a way to solve my problem, but I want to see if there is any better or clear solution for this. I have two associative arrays like this:

$person= [
    "A" => [
            "sur" => "a",
            "fir" => "andras"
            ],
    "C" =>  [
            "sur" => "b",
            "fir" => "balint"
            ]
];
$data = [
    "A" => ["011", "012", "013"],
    "C" => ["021", "022"]
];

I want to map the two arrays if their keys are equal. So the result should look like this:

$person= [
    "A" => [
            "sur" => "a",
            "fir" => "andras",
            "tel" => ["011", "012", "013"]
            ],
    "C" =>  [
            "sur" => "b",
            "fir" => "balint",
            "tel" => ["021", "022"]
            ]
];

My code:

foreach ( array_intersect_key(array_keys($data,$person)) as $id) {
    $person[$id]['tel'] = $data[$id];
}
share|improve this question
    
Welcome to Code Review. Please declare your cross-post – 200_success Nov 25 '15 at 15:34
up vote 1 down vote accepted

As to save some lines of code and to use the appropriate functions that PHP provides then yes, this is a perfect solution.

On the other point of view on somebody who wants to quickly read through your code and know whats happening, then I would have suggested a nested loop.

For both cases, a comment above your loop would be very appreciated.

share|improve this answer
    
Thank you! appreciate that – Hamid Richárd Allili Nov 26 '15 at 11:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.