Prismatic Posted June 12, 2009 Share Posted June 12, 2009 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 ) Link to comment https://forums.phpfreaks.com/topic/161991-solved-simple-way-to-add-an-item-to-an-array-at-a-certain-point-and-push-other-elements/ Share on other sites More sharing options...
Ken2k7 Posted June 12, 2009 Share Posted June 12, 2009 array_splice Link to comment https://forums.phpfreaks.com/topic/161991-solved-simple-way-to-add-an-item-to-an-array-at-a-certain-point-and-push-other-elements/#findComment-854729 Share on other sites More sharing options...
Prismatic Posted June 12, 2009 Author Share Posted June 12, 2009 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); } ?> Link to comment https://forums.phpfreaks.com/topic/161991-solved-simple-way-to-add-an-item-to-an-array-at-a-certain-point-and-push-other-elements/#findComment-854731 Share on other sites More sharing options...
Mark Baker Posted June 12, 2009 Share Posted June 12, 2009 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); Link to comment https://forums.phpfreaks.com/topic/161991-solved-simple-way-to-add-an-item-to-an-array-at-a-certain-point-and-push-other-elements/#findComment-854741 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.