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:

banner for the css playlist in hebrew life michael courses for programmers

The First Steps in CSS

Learn CSS using our our videos (in Hebrew) on the CSS (he) playlist on youtube. Do it now. Do it for free.

Good Trainers Collaborate with Others

It is always essential to keep an open mind and learn from others. This applies to everyone, including teachers and especially software development trainers. Software

The Beauty of Code

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

Update cookies preferences