How can you replicate the functionality of PHP's shuffle() function using only basic loops and if statements, without using array functions like array_values or in_array?
To replicate the functionality of PHP's shuffle() function without using array functions, we can manually shuffle the elements of an array using basic loops and if statements. One way to do this is by swapping elements randomly within the array until all elements have been shuffled.
function custom_shuffle(&$array) {
$count = count($array);
for ($i = $count - 1; $i > 0; $i--) {
$j = mt_rand(0, $i);
if ($j != $i) {
$temp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temp;
}
}
}
// Example usage
$array = [1, 2, 3, 4, 5];
custom_shuffle($array);
print_r($array);
Keywords
Related Questions
- How can regular expressions be used to check for specific character patterns in a string in PHP?
- How can a PHP developer troubleshoot and resolve issues related to Safe Mode restrictions when encountering warnings or errors during file uploads?
- Are there any best practices for using filter_var() and preg_match() functions for form validation in PHP?