This question already has an answer here:
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.
</div>
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
Use asort($array)
to sort an array.
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
";
}
This will output
c = apple
b = banana
d = lemon
a = orange
I would simply use:
$list = array('apple', 'pear', 'kiwi');
sort($list);
var_dump($list);
This is imho the best for not associative arrays.