sort:
- Sorts an array in ascending order by value.
- Syntax:
sort(array &$array, int $sort_flags = SORT_REGULAR): bool
- Example:php
$fruits = ['banana', 'apple', 'cherry']; sort($fruits); print_r($fruits); // Output: ['apple', 'banana', 'cherry']
rsort:
- Sorts an array in descending order by value.
- Syntax:
rsort(array &$array, int $sort_flags = SORT_REGULAR): bool
- Example:php
$fruits = ['banana', 'apple', 'cherry']; rsort($fruits); print_r($fruits); // Output: ['cherry', 'banana', 'apple']
asort:
- Sorts an array in ascending order by value, maintaining key-value pairs.
- Syntax:
asort(array &$array, int $sort_flags = SORT_REGULAR): bool
- Example:php
$fruits = ['b' => 'banana', 'a' => 'apple', 'c' => 'cherry']; asort($fruits); print_r($fruits); // Output: ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry']
arsort:
- Sorts an array in descending order by value, maintaining key-value pairs.
- Syntax:
arsort(array &$array, int $sort_flags = SORT_REGULAR): bool
- Example:php
$fruits = ['b' => 'banana', 'a' => 'apple', 'c' => 'cherry']; arsort($fruits); print_r($fruits); // Output: ['c' => 'cherry', 'b' => 'banana', 'a' => 'apple']
ksort:
- Sorts an array in ascending order by key.
- Syntax:
ksort(array &$array, int $sort_flags = SORT_REGULAR): bool
- Example:php
$fruits = ['b' => 'banana', 'a' => 'apple', 'c' => 'cherry']; ksort($fruits); print_r($fruits); // Output: ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry']
krsort:
- Sorts an array in descending order by key.
- Syntax:
krsort(array &$array, int $sort_flags = SORT_REGULAR): bool
- Example:php
$fruits = ['b' => 'banana', 'a' => 'apple', 'c' => 'cherry']; krsort($fruits); print_r($fruits); // Output: ['c' => 'cherry', 'b' => 'banana', 'a' => 'apple']
These functions provide flexibility in sorting arrays based on both keys and values, as well as in ascending and descending orders. The sort_flags
parameter allows for specifying additional sorting options if needed, such as sorting strings in a case-insensitive manner or sorting based on natural order.
No comments:
Post a Comment