Jump to content

[SOLVED] Simple way to add an item to an array at a certain point and push other elements


Prismatic

Recommended Posts

down?

 

Say I've got an array

 

Array
(
    [1] => url1
    [2] => url2
    [3] => url3
    [4] => url4
)

 

How would I go about making a function that would allow me to insert a new element in spot 2, and have all others move down accordingly so I end up with this?

 

Array
(
    [1] => url1
    [2] => sub_url1
    [3] => url2
    [4] => url3
    [5] => url4
)

Solved.

 

<?php
function array_insert(&$array, $value, $offset)
{
    if (is_array($array)) {
        $array  = array_values($array);
        $offset = intval($offset);
        if ($offset < 0 || $offset >= count($array)) {
            array_push($array, $value);
        } elseif ($offset == 0) {
            array_unshift($array, $value);
        } else {
            $temp  = array_slice($array, 0, $offset);
            array_push($temp, $value);
            $array = array_slice($array, $offset);
            $array = array_merge($temp, $array);
        }
    } else {
        $array = array($value);
    }
    return count($array);
}
?>

function insertIntoArray($array,$newElement,$position) {
    $p1 = array_slice($array,0,$position-1);
    $p2 = array_slice($array,$position-1);
    $p1[] = $newElement;
    return array_merge($p1,$p2);
}

$originalArray = array('url1', 'url2', 'url3', 'url4');
$newArray = insertIntoArray($originalArray,'sub_url1',2);
print_r($newArray);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.