开发者

php push 1 key to end of array

Say I have an array:

$k = array('1', 'a', '2', '3');
开发者_JAVA技巧

I would like to push 'a' to the end of the array. So it would become:

$k = array('1', '2', '3', 'a');

Is there any efficient way to do this?


I think you mean you want to sort the array. You can use PHP's sort() function see the manual for options (like sorting type, you'll probably need SORT_STRING).


$k = array('1', 'a', '2', '3');

$varToMove = $k[1];

unset($k[1]);
$k[] = $varToMove;

var_dump($k);

You'll get:

array(4) {
  [0]=>
  string(1) "1"
  [2]=>
  string(1) "2"
  [3]=>
  string(1) "3"
  [4]=>
  string(1) "a"
}

Just note that key 1 is missing at the moment. Not sure if you care about them though.


Try PHPs natsort function:

<?php

$k = array('1', 'a', '2', '3');
var_dump($k);
natsort($k);
var_dump($k);

Outputs:

array(4) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "a"
  [2]=>
  string(1) "2"
  [3]=>
  string(1) "3"
}
array(4) {
  [0]=>
  string(1) "1"
  [2]=>
  string(1) "2"
  [3]=>
  string(1) "3"
  [1]=>
  string(1) "a"
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜