Copy link to clipboard
Copied
Hello!
I have a question about using function sort();
I set the initial key of array to be 1 (instead of default 0). Everything goes OK until I sort the array. After sorting the array initial key value sets itself back to zero.
Here is the example:
<?php
$var = array(1 => "Good", "Better", "The Best");
foreach ($var as $index => $value)
{
echo $index." - ".$value."<br />";
}
sort($var);
foreach ($var as $index => $value)
{
echo "<br />".$index." - ".$value;
}
?>
How to avoid the change of the initial array key?
The output should be:
1 - Better
2 - Good
3 - The Best
Copy link to clipboard
Copied
DissidentPJ wrote:
I have a question about using function sort();
I set the initial key of array to be 1 (instead of default 0). Everything goes OK until I sort the array. After sorting the array initial key value sets itself back to zero.
Yes, of course, it will. If you read the PHP manual page for sort(), it says quite clearly "This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys."
PHP has a large number of sort functions to handle a variety of requirements. However, what you want to do is to reorder the values AND renumber the keys. The simple way to do it is to use sort(), which puts the values in the right order starting at 0. Just add 1 to the key when you use it.
Copy link to clipboard
Copied
<?php
$var = array(1 => "Good", "Better", "The Best");
foreach ($var as $index => $value)
{
echo $index." - ".$value."<br />";
}
sort($var);
foreach ($var as $index => $value)
{
$index=$index+1;
echo "<br />".$index." - ".$value;
}
?>