PHP insert new value at first index in array

There is no straight forward function to obtain this even though it is very easy to accomplish in .NET with .InsertAt(0). Normally what we need to do in PHP we have to clone a new array by declare a new first value, then continue loop the old array, quite stupid a lot of time I found.

However I just found out an elegant way to do that today.

$ori_categories = $this->Course->Category->find('list', array('order' => 'Category.category'));
$all = array(0 => 'All Categories');
$new_categories = $all + $ori_categories;

see http://tudorbarbu.ninja/insert-at-the-beginning-of-an-array-in-php/

I heard this also true in Javascript 🙂

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