Reputation: 53
Let's say i have this array:
$array = (1,2,4,5);
Now how do i add missing 3 in above array in the correct position index/key-wise?
Upvotes: 5
Views: 170
Reputation: 877
function insertMissingIntoArray($values = array(), $valueIncrement = 1) {
$lastValue = 0;
foreach ($values as $key=>$val) {
if ($key != 0) {
if ($val != $lastValue + $valueIncrement) {
array_splice($values, $key, 0, $val);
}
$lastValue = $val;
}
}
return $values;
}
Used like this:
$values = array(1,2,4,5,7,9);
$fixedValues = insertMissingIntoArray($values, 1);
// $fixedValues now is (1,2,3,4,5,6,7,8,9)
Upvotes: 2
Reputation: 146430
Last but not least:
Upvotes: 2
Reputation: 3204
Maybe I'm missing the complexity of your question, but doesn't the following give you what you want?
$array[] = 3;
sort($array);
Upvotes: 4
Reputation: 6346
function array_insert($array,$pos,$val)
{
$array2 = array_splice($array,$pos);
$array[] = $val;
$array = array_merge($array,$array2);
return $array;
}
usage:
array_insert($a,2,3);
Upvotes: 1
Reputation: 17555
array_merge(array_slice($array,0,2),array(3),array_slice($array,2))
Upvotes: 6
Reputation: 48284
Try:
array_splice($array, 2 /*offset*/, 0 /*length*/, 3 /*value*/);
Note that this will reorder the input array's keys from 0 to n-1.
(Edit: The return value is not used in this case.)
Upvotes: 9