How to make Random Even Number in PHP
If you want to generate a random number that will be also even, there are many possible solutions.
The approach I’d suggest is to generate any random integer, check if it’s even, and if not, just add or subtract 1.
Example:
Make a random even number in specified range.
<?php
$min = 5;
$max = 20;
$random = ( rand($min, $max) );
if($random % 2 !== 0) {
if($random == $max) {
$random = $random - 1;
} else {
$random = $random + 1;
}
}
echo $random;
?>
Ready to use random even number function
<?php
function randomEven($min, $max) {
$random = ( rand($min, $max) );
if($random % 2 !== 0) {
if($random == $max) {
$random = $random - 1;
} else {
$random = $random + 1;
}
}
return $random;
}
// Examples:
echo randomEven(5, 20) . '<br>';
echo randomEven(1, 100);
?>