5

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?

6 Answers 6

9

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I already had corrected my answer. It returns the elements that were extracted, which is nothing in this case. It modifies the original input array by reference.
konforence, -1 turns into +1 ;)
6
array_merge(array_slice($array,0,2),array(3),array_slice($array,2))

Comments

4

Maybe I'm missing the complexity of your question, but doesn't the following give you what you want?

$array[] = 3;
sort($array);

Comments

2

Last but not least:

  1. Append new stuff at the end of the array
  2. Sort the array when you finally need it: asort()

Comments

2
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)

Comments

1
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);

3 Comments

You've actually rebuild array_splice()
That's the reason why there're so many array functions in PHP: writing your own is normally faster that reading the subtleties of built-in ones in the manual :)
wow, we learn something new everyday. thanks for the pointer @Harmen :) +1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.