Currently I’m using foreach to search key when use array_replace:
$grades = array(
0 =>array('id'=>1, 'grade'=>4),
1 =>array('id'=>5, 'grade'=>2),
2 =>array('id'=>17,'grade'=>1),
)
$replacement = array('id'=>17,'grade'=>3);
foreach($grades as $key=>$grade){
if($grade->id ==$replacement['id'] )
$found = $key;
}
$new_grades = array_replace($grades, array($found_key=>$replacement));
I wonder if this will become inefficient when the number of elements grow too much in $grades array. Is there any better way to do the search and replace job?
The execution time grows linearly with the number of elements in the array (
O(N)). Use a better data structure, i.e. use the array in an associative way with the ID as index:Then the lookup cost is constant (
O(1)). You can do:or something similar, depending on your data.