Jump to content

inserting into an array at specific position


severndigital

Recommended Posts

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

 

 

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

 

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

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.