0

I am trying to first sort an array and then displaying it alphabetical order

   $testArray[test] = 'London';
    $testArray[fsee] = 'Cardiff';
    $testArray[pol] = 'Edinburgh';
    $testArray[bede] = 'Manchester';
    asort($testArray);
    foreach ($testArray as $key => $value) {
        echo $key . ' -- ' . $value . '<br/>';
    }

And i like to alphabetical sort on test, fsee, pol and bede, so it return

bede -- Manchester
fsee -- Cardiff
pol -- Edinburgh
test -- London
4
  • 1
    Side note: Make sure your keys are wrapped in at least single quotes when you assign them. Otherwise php has to determine if they are constants first, and then fallback to assuming its not. Throws lots of warnings too with full error reporting on. Commented Dec 10, 2017 at 16:06
  • here is an example like your question look this stackoverflow.com/a/7388926/4499393 Commented Dec 10, 2017 at 16:10
  • @IncredibleHat i am using the following in my php loop and now i am not sure if i need to set $label in single quotes ` if (!array_key_exists($label, $sums)) { $sums[$label] = 0; }` Commented Dec 10, 2017 at 16:14
  • 1
    @alex No. Variables you do not, as they are known as a $variable. Its when you do: $stuff[ something ] that it does not know if something is a constant, or a string to use (like your example code you provided in the Q) $testArray[test] should really be written as $testArray['test'] .. if that helps. Commented Dec 10, 2017 at 16:16

2 Answers 2

5

Use ksort function.

ksort($testArray);
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to perform a very fast sorting ignoring the keys case (your keys seem to be all lower case so a case-insensitive comparison should be good in this situation), use this:

uksort($testArray, "strnatcasecmp");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.