Merge arrays and sort in descending order using PHP

In this article, you can see how to merge arrays and sort using PHP. To achieve this, we going to do it in a simple way and in detail.

Let’s start with this in a step by step: (merge arrays sort PHP)

Main and the important point in this topic is to declare two array.

After declaring of array is done, then we going to merge two array using array function.

To merge an array we going to using array function is called array merge.

Before going through example, first we discuss regarding array merge.

PHP array_merge() Function : Definition and Usage

Definition of array merge is merging to two array in one array.

Important point in this is that you can assign one array or as many.

Below is syntax for array merge function.

array_merge(array1, array2,...)
array1It is required. Represent an array.
array2It is optional. Represent an array.
array3It is optional. Represent an array.
Parameter and Description.

Important point in array merge is that if two or more array have same key then last one get override.

From below example you come to understand regarding array merge function.

 $a1=array(4, 6, 2);
 $a2=array(22, 11);


Array ( [0] => 4 [1] => 6 [2] => 2 [3] => 22 [4] => 11 )

From above example you completely understand regarding array merge.

Now you going to see how to sort an array in descending order in PHP.

Using sort function you sort the merged array in descending order.

There are many sort function for arrays.

Let’s Discuss regarding sort function for array.

sort()Sorting in ascending order.
rsort()Sorting in descending order
asort()According to the value sorting associative arrays in ascending order.
ksort()According to the key sorting associative arrays in ascending order.
arsort()According to the value sorting associative arrays in descending order.
krsort()According to the key sorting associative arrays in descending order.
Sorting Function.

You have to use rsort to sort array in descending array.

“How to display data in Div using PHP”

Below is example and syntax for rsort function.

$a1=array(4, 6, 2);
$a2=array(22, 11);
$numbers = array_merge($a1,$a2);
   $arrlength = count($numbers);
   for($x = 0; $x < $arrlength; $x++) {
	echo $numbers[$x];
	echo "<br>";

From above code example we finally achieve merge of array and sort array in descending order.

I hope you liked my this article. If you have any queries or any question regarding this, Feel free to comment on Me.

Leave a Comment