tags:

views:

55

answers:

3
$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 ?

+1  A: 

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

Tatu Ulmanen
But I don't want to modify the numeric keys,just the order.
wamp
@wamp please provide sample input and output
NullUserException
So you want to have a '-1' key?
Mchl
The unshift stuff will only work when the key is continuous.
wamp
A: 

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

NullUserException
A: 
array_unshift($arr, 'Please select value');

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

Maulik Vora