PHP – Insert and element into a specific position of an Array

Originally we have an array as follow

$fruits = array(
  '0' => 'apple',
  '1' => 'banana',
  '2' => 'pear',
);

 

So i want to insert “melon” into the 2nd position which is after “apple”. We can do it by array_splice().

array_splice($fruits , 1, 0, 'melon');

 

Now we have

$fruits = array(
  '0' => 'apple',
  '1' => 'melon',
  '2' => 'banana',
  '3' => 'pear',
);

 

Done =)

Reference:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s