Last Updated:

Sorting the php array with the preservation of the "switch /value" relationship

The sort() function does not store key/value relationships. Instead, items are indexed ascending from 0.
 
In order to preserve the key/value relationship, you must use the asort() function.
This function allows you to sort arrays with "keys" containing useful information.

Resulting array:


Result:
<?php
$array = array(1 => 'Letter', 'new' => 'House', 'Forest', 'Carpenter', 'pacificsky');
sort($array);
var_dump($array);
?>

array(5) { [4]=> string(10) "pacificsky" [1]=> string(10) "Letter" ["new"]=> string(6) "Home" [2]=> string(6) "Forest" [3]=> string(14) "Carpenter" }


Options for iterating through the array.

First option cycle foreach:


Result:
<?php
$array = array(1 => 'Letter', 'new' => 'House', 'Forest', 'Carpenter', 'pacificsky');
sort($array);
foreach($array as $key => $value) {
echo "Value: {$value} has key: \"{$key}\"<br />\n";
}
?>


Meaning: pacificsky has a key: "4"
Value: The letter has a key: "1"
Value: The house has a key: "new"
Value: The forest has a key: "2"
Value: The carpenter has a key: "3"


The second variant of the loop while


Result:
<?php
$array = array(1 => 'Letter', 'new' => 'House', 'Forest', 'Carpenter', 'pacificsky');
sort($array);
while(list($key, $value) = each($array)) {
echo "Value: {$value} has key: \"{$key}\"<br />\n";
}
?>


Meaning: pacificsky has a key: "4"
Value: The letter has a key: "1"
Value: The house has a key: "new"
Value: The forest has a key: "2"
Value: The carpenter has a key: "3"