// Generic Swap Method
class Utils
{
/**
* @template T
* @param array<int, T> $arr
* @param int $i
* @param int $j
* @return void
*/
public static function swap(array &$arr, int $i, int $j): void
{
$temp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $temp;
}
}
// Test with integers
$numbers = [10, 20, 30, 40];
Utils::swap($numbers, 1, 3);
print_r($numbers);
// Test with strings
$words = ["PHP", "Java", "Python"];
Utils::swap($words, 0, 2);
print_r($words);
/*
run:
Array
(
[0] => 10
[1] => 40
[2] => 30
[3] => 20
)
Array
(
[0] => Python
[1] => Java
[2] => PHP
)
*/