1

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?

2
  • Are you wanting to sort the array alphabetically? Or is your general case that you always want the second element of the array pushed to the back? Commented Sep 20, 2011 at 10:34
  • This is an especially poor/vague minimal reproducible example and I find it to be Unclear and inviting answers that fundamentally execute different techniques but can still generate the desired result. For this reason, this page should be closed until clarified. A good sample array will have enough complexity to differentiate correct answers from incorrect answers. Commented Sep 22, 2022 at 6:53

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.