Sort an array of objects by a field in PHP

Updated

Write a program in Php to sort an array of objects by any object field. Here, we will take a array of student with fields as Id, Name, Marks. Then we will sort the students in the ascending order of marks. We will use a inbuilt function called Usort which takes in two arguments Array and boolean comparator function that will be used to compare two objects on the basis of any fields. We will return true if the Marks of 1st student is greater than that of 2nd student else return false.

Function used: Usort ( Array_Name , Comparator ) Array Name : Name of the array of objects that we want to sort. Comparator : Boolean comparator function that will be used to compare 2 objects.

<?php
// Array of students with Name, Id, Marks
$Students = array(
     array(
         'Name' => 'Dhruv Gupta',
         'Id' => '1',
         'Marks' => '85'
     ),

     array(
         'Name' => 'Naman Khare',
         'Id' => '2',
         'Marks' => '80'
     ),
	 
	 array(
         'Name' => 'Nikhil Rathor',
         'Id' => '3',
         'Marks' => '95'
     ), 
	 array(
         'Name' => 'Aditya Jain',
         'Id' => '4',
         'Marks' => '90'
     )
);

// Displaying array before sorting
echo "Before Sorting!<br>";
foreach ($Students as $Student) {
	echo "Id: {$Student['Id']} Name: {$Student['Name']} Marks :{$Student['Marks']} <br>";
}

// Boolean Comparator for comparing 2 students
function comp($a, $b)
{
	return $a['Marks'] > $b['Marks'] ;
}

// Sorting the array with the 
// help of boolean comparator
usort($Students , function ($a, $b) {
	return $a['Marks'] > $b['Marks'] ;
});

// Displaying the array after sorting
echo "<br>After Sorting!<br>";
foreach ($Students as $Student) {
	echo "Id:{$Student['Id']} Name:{$Student['Name']} Marks: {$Student['Marks']} <br>";
}

Output : Before Sorting! Id: 1 Name: Dhruv Gupta Marks :85 Id: 2 Name: Naman Khare Marks :80 Id: 3 Name: Nikhil Rathor Marks :95 Id: 4 Name: Aditya Jain Marks :90 After Sorting! Id:2 Name:Naman Khare Marks: 80 Id:1 Name:Dhruv Gupta Marks: 85 Id:4 Name:Aditya Jain Marks: 90 Id:3 Name:Nikhil Rathor Marks: 95

Comment
Next tutorial
Mithlesh Upadhyay Published 17 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials