imran haider
imran haider

Reputation: 53

PHP add an item from an array

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

Answers (6)

Anthony Corbelli
Anthony Corbelli

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

Álvaro González
Álvaro González

Reputation: 146430

Last but not least:

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

Upvotes: 2

stevelove
stevelove

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

tpae
tpae

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

bcosca
bcosca

Reputation: 17555

array_merge(array_slice($array,0,2),array(3),array_slice($array,2))

Upvotes: 6

Matthew
Matthew

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

Related Questions