severndigital Posted August 12, 2009 Share Posted August 12, 2009 here is my array Array( [0] = 'Peter' [1] = 'Stewie' [2] = 'Brian' ) I want to add Lois to the array but at position 1 so the array looks like this. Array( [0] = 'Peter' [1] = 'Lois' [2] = 'Stewie' [3] = 'Brian' ) what is the best way to achieve that? My original thought was to make a loop that when it gets to the position inserts the entry and then +1 to rest of the entries. but i figure there must be a better way. thanks, -P Link to comment https://forums.phpfreaks.com/topic/169917-inserting-into-an-array-at-specific-position/ Share on other sites More sharing options...
Daniel0 Posted August 12, 2009 Share Posted August 12, 2009 My original thought was to make a loop that when it gets to the position inserts the entry and then +1 to rest of the entries. That would be the easiest. Link to comment https://forums.phpfreaks.com/topic/169917-inserting-into-an-array-at-specific-position/#findComment-896371 Share on other sites More sharing options...
Mark Baker Posted August 12, 2009 Share Posted August 12, 2009 function arrayInsertAt($array,$entry,$position) { if ($position > 0) { return array_merge(array_slice($array,0,$position),array($entry),array_slice($array,$position)); } else { return array_merge(array($entry),$array); } } $testArray = array('Peter','Stewie','Brian'); $testArray = arrayInsertAt($array,'Lois',1); print_r($testArray); Link to comment https://forums.phpfreaks.com/topic/169917-inserting-into-an-array-at-specific-position/#findComment-896382 Share on other sites More sharing options...
Daniel0 Posted August 12, 2009 Share Posted August 12, 2009 Has a higher space and time complexity though. Might not matter depending on the problem size. Link to comment https://forums.phpfreaks.com/topic/169917-inserting-into-an-array-at-specific-position/#findComment-896393 Share on other sites More sharing options...
aschk Posted August 12, 2009 Share Posted August 12, 2009 A quick alteration to the function supplied by Mark is as follows: function arrayInsertAt($array,$entry,$position) { // At front. if ($position == 0){ array_unshift($array, $entry); return $array; } // At end. if($position == count($position)){ array_push($array, $entry); return $array; } // Greater than end??? if($position > count($position)){ $array[$position] = $entry; return $array; } if ($position > 0) { return array_merge(array_slice($array,0,$position),array($entry),array_slice($array,$position)); } } $testArray = array('Peter','Stewie','Brian'); $testArray = arrayInsertAt($array,'Lois',1); print_r($testArray); Link to comment https://forums.phpfreaks.com/topic/169917-inserting-into-an-array-at-specific-position/#findComment-896409 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.