The code below rounds a value up to a nearest multiple, away from zero. The multiple does not have to be a integer. So you could round, say, to the nearest 25.4, allowing you to round measurements in mm to the nearest inch longer.



<?php

$result = ( ( $y = $x / $c ) == ( $y = (int) $y ) ) ? $x : ( $x >= 0 ?++ $y :-- $y )* $c ;

?>



I originally developed this as an example of write-only code: to make the point that being cleverly terse might save clock ticks but wastes more in programmer time generating un-maintainable code.



The inline code above nests one conditional statement inside another. The value of y changes twice within the same line (three times, if you count the pre-increment). The value of each assignment is used to determine branching within the conditional statement.



How it works can more easily be seen from the expansion below:



<?php

function myCeilingLong ( $x , $c )

{

$a = $x / $c ;

$b = (int) $a ;

if ( $a == $b )

return $x ; else

{

if ( $x >= 0 )

return ( $b + 1 )* $c ; else

return ( $b - 1 )* $c ; }

}

?>



<?php

function myCeilingShort ( $x , $c )

{

return ( ( $y = $x / $c ) == ( $y = (int) $y ) ) ? $x : ( $x >= 0 ?++ $y :-- $y )* $c ;

}

?>



Comparing the versions for speed: the in-line version is about three times faster than myCeilingLong() - but this is almost entirely down to function call overhead.



Putting the in-line code inside the function: the difference in execution speed between myCeilingLong() and myCeilingShort() is around 1.5%.



ceil() is still around 25% faster than the in-line statement so if you are a speed hound your efforts might be better devoted to compiling your own library ...