Hi I am learning php and getting some problem in calculation the ratio of 2 number. Suppose I have in $Var1 = 100 and in $var2 = 40 And I want to show the output 5:2 Any help will be appreciated , Thanks, Pradip
$var1 = 100; $var2 = 40; $den=(int) ($var1 / $var2); $ratio=$var2/$den; $num=$var1/$ratio; PHP: $num and $den are the two answers
No the logic is not correct just use $var1 = 100; $var2 = 50; The ratio should be 2:1 But according to your logic it is giving 4:2 Thanks, Pradip
try this: $var1=12; $var2=40; for($x=$var2;$x>1;$x--) { if(($var1%$x)==0 && ($var2 % $x)==0) { $var1 = $var1/$x; $var2 = $var2/$x; } } echo "$var1 : $var2"; PHP:
The thing your looking for would be to find the greatest common Denominator of both numbers then output the results of dividing those numbers by the GCD. //CREDITS //============================================================ //Author: J. A. Greant ( zak@nucleus.com ) //Version 1: June 9, 2000 //http://www.weberdev.com/get_example-1808.html //============================================================ function GCD ($a, $b) { while ( $b != 0) { $remainder = $a % $b; $a = $b; $b = $remainder; } return abs ($a); } $a = 100; $b = 40; $var = GCD ($a,$b); print $a/$var .':'.$b/$var; PHP: Something of the above will work for you.