$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
?
$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
?
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:
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()
array_unshift($arr, 'Please select value');
use this if you want to add this value on start at first element of array.