sort functions in laravel

  1. 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']
  2. 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']
  3. 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']
  4. 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']
  5. 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']
  6. 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

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...