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

 

 

Link to comment
Share on other sites

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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.