Sorting data and limiting data in PHP

 Sorting data and limiting data in PHP
Sorting data
In PHP, the sort() function is used to sort an indexed array in ascending order and rsort() function is used to sort an indexed array in descending order.

Syntax

sort(array,sortingtype);

Here in the above syntax you have seen different parameters which have been used. Let’s have a look for what purpose they have been used.

    • Array – This parameter is mandatory and used to specify the array to sort.
  • Sortingtype – This parameter is optional and specifies how to compare the array elements. There are number of values have been used to declare the sortingtype:

    0 = This values is used for SORT_REGULAR. It is a by default value which compare the items normally.

    1 = This value is used for SORT_NUMERIC which compare the items numerically.

    2 = This value is used for SORT_STRING which compare items as string.

    3 = This value is used for SORT_LOCALE_STRING which compare items as string based on current locale.

    4 = This value is used for SORT_NATURAL which compare items as string in natural ordering.

Example

Sort the elements of the $numbers array in ascending numerical order:

<?php
$numbers=array(32,6,21,2,50);
sort($numbers);
?>

Limiting Data

In PHP,LIMIT () Function is used to specify the number of records to return.
The LIMIT function makes it easy to code multi page results with SQL, and is very useful on large tables. It can return a large number of records.

Example 

If you want to select records from 1 – 40 from a table employees. Then the code will be

$sql = “SELECT * FROM employees LIMIT 40”;

When the SQL query is run, it will return the first 40 records.