The usort Function in PHP PRO

The usort function allows us to specify the criteria by which the array will be sorted. The following code sample includes the definition of the class Student and the creation of an array that its values are references for objects instantiated from Student. Using the usort function we can sort the students according to their ID numbers or according to any other criteria.

<?php
class Student
{
	private $id;
	private $average;
	private $name;
	function __construct($idVal, $averageVal, $nameVal)
	{
		$this->id = $idVal;
		$this->average = $averageVal;
		$this->name = $nameVal;
	}
	/**
	 *
	 * @return the $id
	 */
	public function getId()
	{
		return $this->id;
	}

	/**
	 *
	 * @return the $average
	 */
	public function getAverage()
	{
		return $this->average;
	}

	/**
	 *
	 * @return the $name
	 */
	public function getName()
	{
		return $this->name;
	}
	public function __toString()
	{
		return $this->getName () . " id=" . $this->getId () . " average=" . $this->getAverage ();
	}
}

$vec = [ 
		new Student ( 123123, 98, "danidin" ),
		new Student ( 523434, 88, "moshe" ),
		new Student ( 456544, 92, "spiderman" ),
		new Student ( 744565, 77, "superman" ) 
];

echo "<h2>before</h2>";
foreach ( $vec as $k => $v )
{
	echo "<Br>$k => " . $v;
}

usort ( $vec, function ($a, $b)
{
	echo "<br>comparing between ".$a->getName()." and ".$b->getName();
	return $a->getId() - $b->getId();
} );

echo "<h2>after</h2>";
foreach ( $vec as $k => $v )
{
	echo "<Br>$k => " . $v;
}

?>

The following video clip shows the execution of this code sample, explains it and shows how easy it is to sort in according to other criterias.

Share:

The Visitor Design Pattern

The Visitor Design Pattern

The visitor design pattern allows us to add operations to objects that already exist without modifying their classes and without extending them.

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences