how to put an array item to the end in php?
I want to put some item of array to the last position , when I loop and output the $arr to html, this will keep the 'other' item always at the end. what is the best and easy way to do it?
<?php
$arr=array(
'a'=>'hello',
'game'=>'boy',
'other'=>'good',
'name'=>'jimmy',
//...
);
// how to resort $arr to put other item to then end of $arr
$arr=array(
'a'=>'hello',
'game'=>'boy',
'name'=>'jimmy',
//...
'other'=>'good'
);
?>
Assuming you're not simply asking to sort the array based on the alphabetical property of the keys, given your array:
$arr=array(
'a'=>'hello',
'game'=>'boy',
'other'=>'good',
'name'=>'jimmy',
);
You have to take the old key out first, while saving its value:
$old = $arr['other'];
unset($arr['other']);
Then, append it to the array like this:
$arr += array('other' => $old);
with the example you have given ksort($arr)
would sort it alphabetically and put the other
item to the end.
second option is to remove the other
item from the array using array_slice
and then placed it in the back using array_merge
First store all the element that you required.
Like
$arr=array( 'a'=>'hello', 'game'=>'boy', 'name'=>'jimmy');
After that add
$arr['other']='good';
Now other element is always at last.....