What is Sorting in PHP


 

What is Sorting in PHP

What is Sorting: This PHP tutorial we discussed about the sorting methods, differences between sorting methods of PHP and other languages like 'C', has an example of selection sort using 'C'-language.

What is Sorting: This PHP tutorial we discussed about the sorting methods, differences between sorting methods of PHP and other languages like 'C', has an example of selection sort using 'C'-language.

What is sorting

Sorting is a process of arranging the elements of an array in a particular order either in ascending order or descending order. Like we have studied  in 'C' -language, Data structure using 'C'/'C++' etc. The following example discussed selection sort using 'c'-language:

main()

{

        int a[]={213,34,45,232,22}, temp, i,j;//initializing the variables

        for(i=0;i<4;i++)

        for(j=i+1;j<5;j++)

        {

                if (a[i] > a[j])

                {

                        temp=a[i];

                        a[i]=a[j];

                        a[j]=temp;

                 }

        }

        printf("\n After sorting the values are:");

        for(i=0;i<5;i++)

        {

                printf("\n %d",a[i]);

        }

}

Output:

22

34

45

213

232

In PHP we need not to sort the elements or develop any algorithm, all we have to do is use the built-in sort() method:

<?php

0

$array=array(213,34,45,232,22);

1

echo"<b>Before sorting:</b><br/>";

print_r($array);

2

echo "<br/><b>After being sort:</b><br/>";

sort($array);

print_r($array);

3

?>

 Before sorting:
Array ( [0] => 213 [1] => 34 [2] => 45 [3] => 232 [4] => 22 )
After being sort:
Array ( [0] => 22 [1] => 34 [2] => 45 [3] => 213 [4] => 232 )

4

Though we know selection sorting is not considered as a good sorting technique, but just for its simplicity we use this sorting algorithm. But in the case of PHP we do not need to sort each element, instead we have so many built-in functions to sort the elements of array like sort(), rsort(), ksort() etc. which are discussed in other web pages. 

Ads