PASSWORD RESET

Your destination for complete Tech news

PHP

How to sort an associative array in PHP?

371 0
< 1 min read

To sort an associative array in PHP, you can use the asort() function. This function sorts an array by the values, while preserving the keys. For example:

$fruits = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');

asort($fruits);

foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}

This would output:

a = apple
b = banana
c = cherry

If you want to sort the array in reverse order, you can use the arsort() function.

If you want to sort the array by the keys, you can use the ksort() function. To sort the array in reverse order by the keys, you can use the krsort() function.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.