1

Trying to sort an array by name so I can display an alphabetical list.

Here's a snippet of code:

sort($stores);

for ($i = 0; $i < count($stores); $i++) {
    echo $stores[$i]['name'];
}

I have a basic understanding of what needs to be done, I'm just not sure how to pass the 'name' part of the array to the sort() function. Perhaps I need to use a different function?

1

2 Answers 2

2

Use a custom sort function:

usort($stores, function ($a, $b) {
    return strcmp($a['name'], $b['name']);
});
Sign up to request clarification or add additional context in comments.

Comments

2

You can use usort to sort an array by values using a customized comparison function.

By custom here we mean an array of custom object types.

function compare($a, $b)
{
    return strcmp($a['name'], $b['name']);
}

usort($stores, "compare");

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.