Reputation: 3
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?
Upvotes: 0
Views: 833
Reputation: 437534
You want a simple loop that starts from $to_insert
and increases the loop variable until it finds a value that does not already exist as a key in $arr
. So you can use for
and array_key_exists
:
for($i = $to_insert; array_key_exists($i, $arr); ++$i) ;
$arr[$i] = $elem;
This will correctly insert the element both when the $to_insert
key exists and when it does not.
Upvotes: 4
Reputation:
The following code will find the next index not in use, starting at $to_insert
:
$to_insert = 25;
$elem = 'new';
for($i = $to_insert; ; $i++)
{
if(!isset($arr[$i]))
{
$arr[$i] = $elem;
break;
}
}
Upvotes: 1