How to Sort an Array containing 1 to n values in PHP ?
Last Updated :
16 Jul, 2024
In this article, we will see how to sort an array that contains 1 to n values in PHP. There are various approaches through which we can sort an array with custom values. Below is an example for a better understanding of the problem statement.
Example:
Input: arr = [3, 1, 4, 5, 2, 8, 9, 5]
Output: Sorted Array is: [1, 2, 3, 4, 5, 8, 9]
Input: arr = [3, 1, 4, 5, 2, 0, 10]
Output: Sorted Array is: [0, 1, 2, 3, 4, 5, 10]
There are two methods to sort an array that contains 1 to n values:
Using PHP sort() Function
We will use the built-in sort() function to sort the input array into ascending to descending order. It sorts the actual array and hence changes are reflected in the original array itself.
Syntax
sort(array &$array, int $sort_flags = SORT_REGULAR): bool
Example: This example uses the built-in sort() function to sort the input array into the correct order.
PHP
<?php
function sortArray($arr)
{
sort($arr);
return $arr;
}
$arr1 = [3, 1, 4, 5, 2, 8, 6, 10, 7];
$arr2 = [3, 1, 4, 5, 2, 0, 10];
$result1 = sortArray($arr1);
$result2 = sortArray($arr2);
echo "Sorted Array is: [" . implode(", ", $result1) . "]\n";
echo "Sorted Array is: [" . implode(", ", $result2) . "]\n";
?>
OutputSorted Array is: [1, 2, 3, 4, 5, 6, 7, 8, 10]
Sorted Array is: [0, 1, 2, 3, 4, 5, 10]
Using a Custom Sorting Algorithm (Bubble Sort)
We will use the Bubble sort algorithm to manually sort the array without relying on any built-in approach to sort the array. Here, the loops are used to iterate over the array elements and sort them in the correct order.
Syntax
function bubbleSort(&$arr) {
$n = count($arr);
for ($i = 0; $i < $n - 1; $i++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
// Swap $arr[$j] and $arr[$j+1]
$temp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $temp;
}
}
}
}
Example: This example uses the custom sorting algorithm (Bubble Sort) to sort the input array elements.
PHP
<?php
function customSortArray($arr)
{
$n = count($arr);
for ($i = 0; $i < $n - 1; $i++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
$temp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $temp;
}
}
}
return $arr;
}
$arr1 = [3, 1, 4, 5, 2, 8, 6, 10, 7];
$arr2 = [3, 1, 4, 5, 2, 0, 10];
$result1 = customSortArray($arr1);
$result2 = customSortArray($arr2);
echo "Sorted Array is: [" . implode(", ", $result1) . "]\n";
echo "Sorted Array is: [" . implode(", ", $result2) . "]\n";
?>
OutputSorted Array is: [1, 2, 3, 4, 5, 6, 7, 8, 10]
Sorted Array is: [0, 1, 2, 3, 4, 5, 10]
Using a Custom Sorting Algorithm (Quicksort)
We will use the Quicksort algorithm to manually sort the array without relying on any built-in approach to sort the array. Quicksort is a divide-and-conquer algorithm that is efficient for large datasets.
PHP
<?php
function quickSort(&$arr) {
if(count($arr) < 2) {
return $arr;
}
$left = $right = array();
reset($arr);
$pivot_key = key($arr);
$pivot = array_shift($arr);
foreach($arr as $k => $v) {
if($v < $pivot)
$left[$k] = $v;
else
$right[$k] = $v;
}
return array_merge(quickSort($left), array($pivot_key => $pivot), quickSort($right));
}
$arr1 = [3, 1, 4, 5, 2, 8, 6, 10, 7];
$arr2 = [3, 1, 4, 5, 2, 0, 10];
$result1 = quickSort($arr1);
$result2 = quickSort($arr2);
echo "Sorted Array is: [" . implode(", ", $result1) . "]\n";
echo "Sorted Array is: [" . implode(", ", $result2) . "]\n";
?>
OutputSorted Array is: [1, 2, 3, 4, 5, 6, 7, 8, 10]
Sorted Array is: [0, 1, 2, 3, 4, 5, 10]
Using a Custom Sorting Algorithm (Insertion Sort)
Insertion Sort is a simple and efficient comparison-based sorting algorithm. It builds the final sorted array one item at a time, with each iteration removing an element from the input data and inserting it into the correct position in the already sorted part of the array.
Example: This example uses the custom sorting algorithm (Insertion Sort) to sort the input array elements.
PHP
<?php
function insertionSort(&$arr) {
$n = count($arr);
for ($i = 1; $i < $n; $i++) {
$key = $arr[$i];
$j = $i - 1;
// Move elements of $arr[0..$i-1], that are greater than $key, to one position ahead of their current position
while ($j >= 0 && $arr[$j] > $key) {
$arr[$j + 1] = $arr[$j];
$j--;
}
$arr[$j + 1] = $key;
}
}
$arr1 = [3, 1, 4, 5, 2, 8, 6, 10, 7];
$arr2 = [3, 1, 4, 5, 2, 0, 10];
insertionSort($arr1);
insertionSort($arr2);
echo "Sorted Array is: [" . implode(", ", $arr1) . "]\n";
echo "Sorted Array is: [" . implode(", ", $arr2) . "]\n";
?>
OutputSorted Array is: [1, 2, 3, 4, 5, 6, 7, 8, 10]
Sorted Array is: [0, 1, 2, 3, 4, 5, 10]
Using Merge Sort
Merge Sort is a divide-and-conquer algorithm that recursively divides the array into halves, sorts each half, and then merges the sorted halves to produce a sorted array. Merge Sort is efficient for large datasets and has a time complexity of O(n log n).
Example:
PHP
<?php
function mergeSort($arr) {
if (count($arr) <= 1) {
return $arr;
}
$mid = floor(count($arr) / 2);
$left = array_slice($arr, 0, $mid);
$right = array_slice($arr, $mid);
$left = mergeSort($left);
$right = mergeSort($right);
return merge($left, $right);
}
function merge($left, $right) {
$result = [];
$i = 0;
$j = 0;
while ($i < count($left) && $j < count($right)) {
if ($left[$i] < $right[$j]) {
$result[] = $left[$i];
$i++;
} else {
$result[] = $right[$j];
$j++;
}
}
while ($i < count($left)) {
$result[] = $left[$i];
$i++;
}
while ($j < count($right)) {
$result[] = $right[$j];
$j++;
}
return $result;
}
$arr = [3, 1, 4, 5, 2, 8, 9, 5];
$sortedArray = mergeSort($arr);
echo "Sorted Array is: ";
print_r($sortedArray);
?>
OutputSorted Array is: Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 5
[6] => 8
[7] => 9
)
Similar Reads
How to Check an Array is Sorted or Not in PHP? Given an array, the task is to check whether the given array is sorted or not. Arrays are often used to store and manipulate data. One common task is to check if an array is sorted in ascending or descending order. This article will explore different approaches to determine whether an array is sorte
3 min read
How to find the index of an element in an array using PHP ? In this article, we will discuss how to find the index of an element in an array in PHP. Array indexing starts from 0 to n-1. Here we have some common approachesTable of ContentUsing array_search() FunctionUsing array_flip()Using a custom functionUsing a foreach LoopUsing array_keys FunctionUsing ar
6 min read
How to Slice an Array in PHP? In PHP, slicing an array means taking a subset of the array and extracting it according to designated indices. When you need to extract a subset of elements from an array without changing the original array, this operation comes in handy. PHP comes with a built-in function called array_slice() to he
2 min read
Sort an Associative Array by Key in PHP Given an Associative Array, the task is to sort the associative array by its keys in PHP. There are different methods to sort Associative Array by keys, these are described below: Table of ContentUsing ksort() FunctionUsing uksort() FunctionConverting to a Regular Array for SortingUsing array_multis
3 min read
Sort an array of dates in PHP We are given an array of multiple dates in (Y-m-d) format. We have to write a program in PHP to sort all the dates in the array in decreasing order. Examples : Input : array("2018-06-04", "2014-06-08", "2018-06-05") Output : 2018-06-05 2018-06-04 2014-06-08 Input : array("2016-09-12", "2009-09-08",
2 min read
Find the Second Largest Element in an Array in PHP We will be given with an integer array, i.e. $array1 or $ array2, and the task is to find the second largest element in the array. There are multiple ways to approach and solve this problem however using sorting is the most common and concise approach as we use the rsort() function for further opera
3 min read
How to Switch the First Element of an Arrays Sub Array in PHP? Given a 2D array where each element is an array itself, your task is to switch the first element of each sub-array with the first element of the last sub-array using PHP.Example:Input: num = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']];Output: [ ['g', 'b', 'c'], ['d', 'e', 'f'], ['a', 'h', '
2 min read
PHP program to find the maximum and the minimum in array Finding the maximum and minimum in an array involves determining the largest and smallest values within a given set of numbers. This task is crucial for analyzing data, identifying trends, or filtering outliers. Various methods, from simple traversal to optimized algorithms, can achieve this.Example
7 min read
How to remove duplicate values from array using PHP? In this article, we will discuss removing duplicate elements from an array in PHP. We can get the unique elements by using array_unique() function. This function will remove the duplicate values from the array.Syntax:array array_unique($array, $sort_flags);Note: The keys of the array are preserved i
4 min read
How to get elements in reverse order of an array in PHP ? An array is a collection of elements stored together. Every element in an array belong to a similar data type. The elements in the array are recognized by their index values. The elements can be subjected to a variety of operations, including reversal. There are various ways to reverse the elements
4 min read