Giving an aspect ratio X:Y
, is it possible to get its lowest terms?
For example, if an aspect ratio is 6:4
, I want to get 3:2
And if an aspect ratio is 16:10
, I want to get 8:5
X
and Y
are both positive integers
You need to use the function gmp_gcd
GMP gmp_gcd ( GMP $a , GMP $b )
Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.
http://php.net/manual/en/function.gmp-gcd.php
You would divide each side of the ratio by the given result to find the lowest ratio.
You can use phospr/fraction for simplification and convert from float number to fraction, which cover all possible aspect.
In your case you can use like below
<?php
function fraction($n,$d){
$a = abs($n);
$b = abs($d);
if ($a < $b) {
$c = $a;
$a = $b;
$b = $c;
}
$r = $a % $b;
while ($r > 0) {
$a = $b;
$b = $r;
$r = $a % $b;
}
$gcd = $b;
$n /= $gcd;
$d /= $gcd;
return "$n:$d";
}
$ar_str = '6:4';
$ar_arr = explode(":",$ar_str);
$simplified = fraction($ar_arr[0],$ar_arr[1]);
echo "Simplified of $ar_str is : ".$simplified;
?>