# How many digits does an integer have?
#--------------------------------------------------------functiondigit_count($n,$base=10) {
if($n==0) return1;
if($base==10) {# using the built-in log10(x)
# might be more accurate than log(x)/log(10).return1+floor(log10(abs($n)));
}else{# here logB(x) = log(x)/log(B) will have to do.return1+floor(log(abs($n))/log($base));
}
}# Example: How many decimal digits for 2 to the power 24?echodigit_count(pow(2,24));# Example: How many bits to write 1 billion in binary, last century?if($country_code=='US') echodigit_count(pow(10,9),2);
if($country_code=='UK') echodigit_count(pow(10,12),2);#--------------------------------------------------------
# Using log to format columns.
#--------------------------------------------------------
# Suppose we have a dynamically generated list of integers,
# and want to present them as a table. The use of log10 in
# our digit_count helps calculate the proper format string.functionprint_list_of_ints($ints,$line_width=40) {# Apply our digit_count to the max int among ints.$field_width=2+digit_count(max($ints));# Create format string for printf.$format="%${field_width}d";$ints_per_line=floor($line_width/$field_width);$border=str_repeat("-",$ints_per_line*$field_width);
echo"\n$border\n";
foreach($intsas$count=>$int) {
if($countand ($count%$ints_per_line==0)) echo"\n";printf($format,$int);
}
echo"\n$border\n";
}# To generate an example, here is a basic function
# returning a list of (pseudo) random numbers.functionrands($how_many) {
for($i=0;$i
return$rands;
}# Example: A list of random ints dynamically formatted into columns.print_list_of_ints(rands(11));/* Sample output. Numbers and fonts vary. Visualize monospace!
------------------------------------
1093146637 244503173 1346204527
638304372 140216732 1054707210
573915416 1728677954 2038899669
534854768 12674586
------------------------------------
*/?>