I had to write the code to get percentage every time I needed it, so I thought it'd be much better to have a function for the purpose, here's the function I wrote. PHP: function percentage($int1, $int2) { $per = $int1 / $int2; $res = $per * 100; return $res; }
This is not a good way of doing it as you may not get correct results. I am not sure about it in PHP but let me know what is the output for the forllowing. $int1 = 48 $int2 = 100
By default there is not data type specified to a variable, it takes the data type of the value assigned. e.g. $a = 10/6; here $a becomes float, and $a = 10/2 here $a becomes int and $a = 'Shabbir' here $a becomes string. So in this case $per = $int1 / $int2; $per becomes float.
I would suggest that the parameters shouldn't be ints, anyway. Someone might want to know the percentage of a fractional number. Someone also might think that the return type has been coerced to match an the input arguments (integers), rather than having been set by PHPs "autotyping". I would also suggest that the relationship, a/b*100, is far too simple to waste the overhead of a function call. On the other hand, I come from the days when resources weren't so abundant that one could be profligate with them.