1

I have two arrays, each with a different structure:

$websites = Array (
     [1131] => Array (
          [httpcode] => 403
          [user_id] => 265
     )

     [1130] => Array (
          [httpcode] => 403
          [user_id] => 265
     )
)

$responses = Array (
     [1131] => 200
     [1130] => 500
)

I am using a nested foreach loop to replace the httpcode in the $websites array with the corresponding new httpcode in the $responses array:

foreach ($websites as $site_id => &$details) {
    foreach ($responses as $resp_id => $new_http)  {
        if ($site_id == $resp_id) {
            $details['httpcode'] = $new_http;
        }  
    }        
}

This works successfully and I get the correct result:

$websites = Array (
     [1131] => Array (
          [httpcode] => 200
          [user_id] => 265
     )

     [1130] => Array (
           [httpcode] => 500
           [user_id] => 265
     )
)

However, I understand that nested foreach loops have a high cost in CPU cycles, and I would like to know if there is a more efficient way of doing this for large arrays with respect to minimising CPU use on a server.

2 Answers 2

1

Second loop is completely pointless. This would suffice:

foreach ($websites as $site_id => &$details) {
    $details['httpcode'] = $responses[$site_id];
}

In case both arrays may not be in sync, you would need to add additional key check:

foreach ($websites as $site_id => &$details) {
    if (array_key_exists($site_id, $responses)) {
        $details['httpcode'] = $responses[$site_id];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

If the array keys are identical:

foreach(array_keys($websites) as $key) {
  $websites[$key]['httpcode'] = $responses[$key];
}

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.