I've tried to write a function that will take an array of different amounts and align the decimal places, by adding the appropriate amount of
to each number with a lesser length than the number with longest length.
It seems pretty long though, and I wonder if anyone has some insight on how I could make is shorter and more efficient.
$arr = array(12, 34.233, .23, 44, 24334, 234);
function align_decimal ($arr) {
$long = 0;
$len = 0;
foreach ( $arr as &$i ){
//change array elements to string
(string)$i;
//if there is no decimal, add '.00'
//if there is a decimal, add '00'
//ensures that there are always at least two zeros after the decimal
if ( strrpos( $i, "." ) === false ) {
$i .= ".00";
} else {
$i .= "00";
}
//find the decimal
$dec = strrpos( $i, "." );
//ensure there are only two decimals
//$dec+3 is the decimal plus two characters
$i = substr_replace($i, "", $dec+3);
//if $i is longer than $long, set $long to $i
if ( strlen($i) >= strlen($long) ) {
$long = $i;
}
}
//locate the decimal in the longest string
$long_dec = strrpos( $long, "." );
foreach ( $arr as &$i ) {
//difference between $i and $long position of the decimal
$z = ( $long_dec - strrpos( $i, "." ) );
$c = 0;
while ( $c <= $z ) {
//add a for each number of characters
//between the two decimal locations
$i = " " . $i;
$c++;
}
}
return $arr;
}
it works okkaaay... just seems really verbose. I'm sure there are a million ways to make it much shorter and more professional. Thanks for any ideas!