Patrick
Patrick

Reputation: 4905

php push 1 key to end of array

Say I have an array:

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

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?

Upvotes: 1

Views: 184

Answers (3)

BMBM
BMBM

Reputation: 16013

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"
}

Upvotes: 0

Ondrej Slint&#225;k
Ondrej Slint&#225;k

Reputation: 31910

$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.

Upvotes: 1

user254875486
user254875486

Reputation: 11240

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

Upvotes: 2

Related Questions