How can I check if a number is a multiple of the input - PHP
Asked Answered
I

5

6

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?

Impair answered 6/3, 2018 at 7:28 Comment(0)
E
12

Use the % operator.

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
Easeful answered 6/3, 2018 at 7:30 Comment(1)
–1; Mixing javascript with php is evil ;(Tartaric
E
3

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.

http://php.net/manual/en/language.operators.arithmetic.php

Education answered 6/3, 2018 at 7:32 Comment(0)
G
2

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
Gook answered 6/3, 2018 at 7:30 Comment(0)
B
2

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"; }
Beaverette answered 6/3, 2018 at 7:40 Comment(1)
Like the idea but it can be simplified even more. What you actually are checking is if the result is an integer. So if(is_int($result))Greggs
L
0

You can use % operator

function check($a,$b){
   if($b % $a > 0){
     return 0;
   }
   else{
    return 1;
   }
}
Lowenstern answered 6/3, 2018 at 7:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.