-1

Here is an array:

$array = (0 => "pear", 1 => "apple", 2 => "orange", 3 => "kiwi");

What is the best way to reorder the array to become:

$array = (0 => "pear", 1 => "kiwi", 2 => "orange", 3 => "apple");

Edit:

Please note I am not looking for an alphabetical sort. I am looking to switch the order of two items within an array. My initial thought was to pop out the key=>value pair that I want to change, then reinsert it. But I want to know if there is a better way.

Willow
  • 1,040
  • 2
  • 10
  • 21
  • [Duplicate of http://stackoverflow.com/questions/1673259/sort-array-by-value-alphabetically-php](http://stackoverflow.com/questions/1673259/sort-array-by-value-alphabetically-php) – aqua May 25 '13 at 23:45
  • Start by looking at sort() and asort() Also see: http://stackoverflow.com/questions/1673259/sort-array-by-value-alphabetically-php -or - are you really trying to change the keys? – eaton9999 May 25 '13 at 23:47
  • Sorry guys, I noticed that it looked like I wanted a sort. That was not actually my intention. I need to switch the order of two items in an array. It has nothing to do with the key's value. – Willow May 26 '13 at 00:22

4 Answers4

2

Use this code to switch 2 values of your array:

$tmp = $array[1];
$array[1] = $array[3];
$array[3] = $tmp;
unset($tmp); // you may delete the variable if you no longer need it
Jocelyn
  • 11,209
  • 10
  • 43
  • 60
1

I think you can use asort to sort your array alphabetically

General example

$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}

This will output

c = apple
b = banana
d = lemon
a = orange
Fabio
  • 23,183
  • 12
  • 55
  • 64
0

Use asort($array) to sort an array.

Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
Farkie
  • 3,307
  • 2
  • 22
  • 33
0

I would simply use:

$list = array('apple', 'pear', 'kiwi');
sort($list);
var_dump($list);

This is imho the best for not associative arrays.

Gizzmo
  • 691
  • 8
  • 21