Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Sort Array in Ascending Order – sort()

Sort Array in Ascending Order – sort()

PHP, being one of the most popular server-side scripting languages, provides developers with a plethora of built-in functions to manipulate arrays effectively. Sorting arrays is a common operation in programming, and PHP offers a straightforward solution for this task with the sort() function. In this article, we will explore how to utilize the sort() function to sort arrays in ascending order, understand its usage, and explore some practical examples.

Understanding the sort() function

The sort() function in PHP is designed to sort an array in ascending order. It alters the original array by rearranging its elements, ensuring they are arranged from the lowest to the highest value. It works efficiently for numeric and string-based arrays.

bool sort(array &$array, int $sort_flags = SORT_REGULAR)

Title: Sort Array in Ascending Order using sort() in PHP

Introduction

PHP, being one of the most popular server-side scripting languages, provides developers with a plethora of built-in functions to manipulate arrays effectively. Sorting arrays is a common operation in programming, and PHP offers a straightforward solution for this task with the sort()  function. In this article, we will explore how to utilize the sort()  function to sort arrays in ascending order, understand its usage, and explore some practical examples.

Understanding the sort() function

The sort()  function in PHP is designed to sort an array in ascending order. It alters the original array by rearranging its elements, ensuring they are arranged from the lowest to the highest value. It works efficiently for numeric and string-based arrays.

Syntax:

bool sort(array &$array, int $sort_flags = SORT_REGULAR)

Parameters:

  • $array : The array to be sorted. Note that it is passed by reference, meaning the original array is modified directly.
  • $sort_flags : (Optional) This parameter is used to define the sorting behavior. It supports various sorting options, such as SORT_NUMERIC, SORT_STRING, SORT_LOCALE_STRING , etc. If not provided, the default value is SORT_REGULAR, which compares items normally.

Return value: The sort()  function returns a boolean value. It returns true  on success and false on failure.

Sorting an array in ascending order

To sort an array in ascending order, you can simply call the sort()  function with the array you wish to sort as the parameter.

Example

$numbers = [4, 1, 7, 2, 5]; 
sort($numbers);
 print_r($numbers);

Output

Array (
 [0] => 1 
 [1] => 2
 [2] => 4
 [3] => 5
 [4] => 7 
)
Facebook
Twitter
LinkedIn
Pinterest
WhatsApp
Scroll to Top