Search code examples
phparraysperformanceforeachprocessing-efficiency

Replacing a nested foreach loop with something more efficient in PHP


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.


Solution

  • 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];
        }
    }