I have a source array, in foreach() loop a new array will be generated based on some field of the source array. And finally the function will return the new array.
function get_role_info() {
$source_array = array(
'role1' => array(
'name' => 'Eric',
'age' => '30',
'gender' => 'male'
),
'role2' => array(
'name' => 'Emily',
'age' => '27',
'gender' => 'female'
)
......
);
foreach ($source_array as $role_name => $role) {
$new_info= array();
$new_info['role-name'] = $role_name;
$new_storage['user-name'] = $role['name'];
...... //other filters
$newinfo[] = $new_info;
}
return $newinfo;
}
The calling of this function will cause CPU utilization increase a lot. If I change foreach to a for loop
for ($i=0; $i<$cnt; $i++) {
....... // same logic to filter fields
}
The CPU utilization will go down... I'm not sure what's the differences between these 2? If I just print the new array and not return it, the CPU will not grow high either. Does anyone have some clue about it? Thx.
Each foreach
iteration returns a copy of the actual data you have in the array, if it is a large array and/or multidimensional, you are operating on copied data and then returning $newInfo
and thats why the CPU doesn't agree with you in this case I guess.
for
loop on the other hand is just looping until you tell it to stop (until $i < $cnt
for example), it doesn't care what changes you're applying where, and it certainly doesn't copy anything over to anywhere. It just loops.
Also, http://php.net/manual/en/control-structures.foreach.php recommends you to unset($source_array)
before you continue with your script (as it is copied, and you have two arrays in memory now)
just found this:
Read more: Performance of FOR vs FOREACH in PHP