How to use usort() Function with Custom Comparison Function In PHP

The usort() function allows you to sort an array using a user-defined comparison function. By using a comparison function that returns a random value, you can achieve array randomization.

PHP




<?php
  
$arr = [1, 2, 3, 4, 5];
  
// Randomize the order of the array
usort($arr, function () {
    return rand(-1, 1);
});
  
// Display the randomized array
print_r($arr);
  
?>


Output

Array
(
    [0] => 2
    [1] => 1
    [2] => 3
    [3] => 4
    [4] => 5
)


How to Randomize the Order of an Array in PHP ?

Randomizing the order of an array is a common operation in PHP, especially when dealing with datasets or when you want to shuffle the presentation of items. In this article, we will explore various approaches to randomize the order of an array.

Table of Content

  • Using shuffle() Function
  • Using usort() Function with Custom Comparison Function

Similar Reads

Using shuffle() Function

The shuffle() function is a built-in PHP function specifically designed for randomizing the order of an array....

Using usort() Function with Custom Comparison Function

...