Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
0

sort(); changes key numbers of array

Explorer ,
Dec 13, 2010 Dec 13, 2010

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

TOPICS
Server side applications

Views

870
Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Dec 13, 2010 Dec 13, 2010

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.

Votes

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Dec 14, 2010 Dec 14, 2010

Copy link to clipboard

Copied

LATEST

<?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;
}


?>

Votes

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines