Reputation: 1727
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?
Upvotes: 1
Views: 167
Reputation: 816334
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:
$grades = array(
1 => array('grade'=>4),
5 => array('grade'=>2),
17 => array('grade'=>1)
);
Then the lookup cost is constant (O(1)
). You can do:
$grades[$replacement['id']] = array('grade' => $replacement['grade']);
or something similar, depending on your data.
Upvotes: 5
Reputation: 124277
Yeah, that can be done vastly more efficiently.
$grades = array(
1 => 4,
5 => 2,
17 => 1,
);
$replacement = array(
17 => 3,
);
$grades = array_merge($grades, $replacement);
If you need more information associated with the ID than just the grade, then you'll still need a more involved data structure like Felix Kling has. But no such requirement is present in your question so I'm not assuming it.
Upvotes: 4