Sorting Array of Objects Using PHP

Consider you have an array or list of objects and wanted to sort it based on one attribute of objects. If the array consists of integer, it is very easy to sort it ascendingly using sort() function, otherwise if the array consists of objects, you have to create custom sorting function which is passed to the PHP usort() function.

Here is an example on how to manually sort array of objects in PHP:

<?php 
class Individual { 	
    private $name = null;     
    public $length = 0;     

    function __construct($name, $length){     	
        $this->name = $name;
    	$this->length = $length;
    }
}

function psort($a,$b){
 if($a->length == $b->length) return 0;
 return ($a->length > $b->length ? 1 : -1);
}

$population = array();
$population[] = new Individual('Ben',100);
$population[] = new Individual('Deerp',50);
$population[] = new Individual('Sheep',120);
$population[] = new Individual('Garet',20);

print_r($population);

usort($population, 'psort');

print_r($population);

The psort() is the custom sorting function to sort the array of objects based on object’s length attribute. Below is the output of the above code:

Array
(
    [0] => Individual Object
        (
            [name:Individual:private] => Ben
            [length] => 100
        )
    [1] => Individual Object
        (
            [name:Individual:private] => Deerp
            [length] => 50
        )
    [2] => Individual Object
        (
            [name:Individual:private] => Sheep
            [length] => 120
        )
    [3] => Individual Object
        (
            [name:Individual:private] => Garet
            [length] => 20
        )
)
Array
(
    [0] => Individual Object
        (
            [name:Individual:private] => Garet
            [length] => 20
        )
    [1] => Individual Object
        (
            [name:Individual:private] => Deerp
            [length] => 50
        )
    [2] => Individual Object
        (
            [name:Individual:private] => Ben
            [length] => 100
        )
    [3] => Individual Object
        (
            [name:Individual:private] => Sheep
            [length] => 120
        )
)

The first Array is the array before sorting and the second one after sorting has been done.

4 Replies to “Sorting Array of Objects Using PHP”

  1. Pingback: Sorting Array of Objects using Ruby and Python | Chisiki No Yama

Leave a Reply

Your email address will not be published. Required fields are marked *

*