wamp
wamp

Reputation: 5949

How to make an array element the first entry in PHP?

$arr = explode(',', $str);
$arr[0] = 'Please select value';

The above makes key 0 the last element ,how to make it first except sort the $arr ?

Upvotes: 1

Views: 1892

Answers (3)

Maulik Vora
Maulik Vora

Reputation: 2584

array_unshift($arr, 'Please select value');

use this if you want to add this value on start at first element of array.

Upvotes: 2

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124778

Use array_unshift:

array_unshift($arr, 'Please select value');

If you want to retain the array keys, you have to go hacky. I don't recommend this though, but it should work:

$arr = array_merge(array("something" => 'Please select value'), $arr);

The new element has to have some key that doesn't exist in $arr, it doesn't have to be "something". If you'd use a numerical index, array_merge would renumber the items starting from zero. So it has to be a string if you really need it to work this way.

Working example:

http://codepad.org/0ZcPpppe

Upvotes: 1

NullUserException
NullUserException

Reputation: 85468

It doesn't really make a difference whether it's the first or last element if you are accessing it via $arr[0]. (arrays in PHP are really maps). An array that's like:

array (
    [1] => 'Hello',
    [0] => 'World
)

For the most part, will behave just like:

array (
    [0] => 'World',
    [1] => 'Hello'
)

But if you insist in having it in the beginning you can use array_unshift()

Upvotes: 0

Related Questions