What I am trying to build is a function that takes an input number and checks if the following number is a multiple of that number.
function checkIfMult($input,$toBeChecked){
// some logic
}
example:
checkIfMult(2,4) // true
checkIfMult(2,6) // true
checkIfMult(2,7) // false
checkIfMult(3,6) // true
checkIfMult(3,9) // true
checkIfMult(3,10) // false
My first instinct was to use arrays
$tableOf2 = [2,4,6,8,10,12,14,16,18]
But then a call like this would be highly unpractical:
checkIfMult(6,34234215)
How can I check to see if something is a multiple of the input?
The Modulo operator divides the numbers and returns the remainder.
In math, a multiple means that the remainder equals 0.
function checkIfMult($input,$toBeChecked){
return $toBeChecked % $input === 0;
}
function checkIfMult($input, $toBeChecked){
console.log('checkIfMult(' + $input +',' + $toBeChecked + ')', $toBeChecked % $input === 0);
return $toBeChecked % $input === 0;
}
checkIfMult(2,4) // true
checkIfMult(2,6) // true
checkIfMult(2,7) // false
checkIfMult(3,6) // true
checkIfMult(3,9) // true
checkIfMult(3,10) // false
</div>
You can modulo %
Like:
In computing, the
modulo
operation finds the remainder after division of one number by another (sometimes called modulus).
function checkIfMult($input,$toBeChecked){
return !( $toBeChecked % $input );
}
This follow the result
echo "<br />" . checkIfMult(2,4); // true
echo "<br />" . checkIfMult(2,6); // true
echo "<br />" . checkIfMult(2,7); // false
echo "<br />" . checkIfMult(3,6); // true
echo "<br />" . checkIfMult(3,9); // true
echo "<br />" . checkIfMult(3,10); // false
You can use the modulus operator, if the result is 0 then the function should return true. The modulus operator (%) performs a division and returns the remainder.
You can use % operator
function check($a,$b){
if($b % $a > 0){
return 0;
}
else{
return 1;
}
}
Alternatively, You can also divide the $tobechecked by $input and check if there is a remainder by using the floor function.
if(is_int($result))
{ echo "It is a multiple";
}
else
{ echo "It isn't a multiple"; }