I want to insert a element inside a array, but not overwrite any existing elements:
$to_insert = 25;
$elem = 'new';
$arr = array(
5 => 'abc',
10 => 'def',
12 => 'xyz',
25 => 'dontoverwrite',
30 => 'fff',
);
foreach($arr as $index => $val){
if($to_insert == $index){
// here get next free index, in this case would be 26;
$arr[$the_free_index] = $elem;
}
}
How can I do that?
You want a simple loop that starts from
$to_insertand increases the loop variable until it finds a value that does not already exist as a key in$arr. So you can useforandarray_key_exists:This will correctly insert the element both when the
$to_insertkey exists and when it does not.See it in action.