PHP 8.5.0 Alpha 2 available for testing

Voting

: max(four, two)?
(Example: nine)

The Note You're Voting On

wbcarts at juno dot com
16 years ago
COMPARING OBJECTS using PHP's usort() method.

PHP and MySQL both provide ways to sort your data already, and it is a good idea to use that if possible. However, since this section is on comparing your own PHP objects (and that you may need to alter the sorting method in PHP), here is an example of how you can do that using PHP's "user-defined" sort method, usort() and your own class compare() methods.

<?php

/*
* Employee.php
*
* This class defines a compare() method, which tells PHP the sorting rules
* for this object - which is to sort by emp_id.
*
*/
class Employee
{
public
$first;
public
$last;
public
$emp_id; // the property we're interested in...

public function __construct($emp_first, $emp_last, $emp_ID)
{
$this->first = $emp_first;
$this->last = $emp_last;
$this->emp_id = $emp_ID;
}

/*
* define the rules for sorting this object - using emp_id.
* Make sure this function returns a -1, 0, or 1.
*/
public static function compare($a, $b)
{
if (
$a->emp_id < $b->emp_id) return -1;
else if(
$a->emp_id == $b->emp_id) return 0;
else return
1;
}

public function
__toString()
{
return
"Employee[first=$this->first, last=$this->last, emp_id=$this->emp_id]";
}
}

# create a PHP array and initialize it with Employee objects.
$employees = array(
new
Employee("John", "Smith", 345),
new
Employee("Jane", "Doe", 231),
new
Employee("Mike", "Barnes", 522),
new
Employee("Vicky", "Jones", 107),
new
Employee("John", "Doe", 2),
new
Employee("Kevin", "Patterson", 89)
);

# sort the $employees array using Employee compare() method.
usort($employees, array("Employee", "compare"));

# print the results
foreach($employees as $employee)
{
echo
$employee . '<br>';
}
?>

Results are now sorted by emp_id:

Employee[first=John, last=Doe, emp_id=2]
Employee[first=Kevin, last=Patterson, emp_id=89]
Employee[first=Vicky, last=Jones, emp_id=107]
Employee[first=Jane, last=Doe, emp_id=231]
Employee[first=John, last=Smith, emp_id=345]
Employee[first=Mike, last=Barnes, emp_id=522]

Important Note: Your PHP code will never directly call the Employee's compare() method, but PHP's usort() calls it many many times. Also, when defining the rules for sorting, make sure to get to a "primitive type" level... that is, down to a number or string, and that the function returns a -1, 0, or 1, for reliable and consistent results.

Also see: http://www.php.net/manual/en/function.usort.php for more examples of PHP's sorting facilities.

<< Back to user notes page

To Top