开发者

php push 1 key to end of array

开发者 https://www.devze.com 2023-04-05 22:10 出处:网络
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:

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

精彩评论

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