I want to add leading zero to a variable to obtain a 6 digits string.
I use this code
echo str_pad( $var, 6, '0', STR_PAD_LEFT ) . str_pad( $var2, 6, '0', STR_PAD_LEFT );
It’s alright but if $var or $var2 is empty, the result is 000000
If $var or $var2 don’t exist, the result of str_pad must be empty for me
I can use
if( $var ){
$test1 = str_pad( $var, 6, '0', STR_PAD_LEFT );
}
if( $var2 ){
$test1 .= str_pad( $var2, 6, '0', STR_PAD_LEFT );
}
echo $test1;
I just want to know if that code can be much clean or simplier.
Thanks.
EDIT: I tried another solution:
function addZero( $number, $length ){
if( !$number ){ return false; }
return str_pad( $number, $length, '0', STR_PAD_LEFT);
}
and just
echo addZero( $var, 6) . addZero( $var2, 5);
Ugly ?
Well, you could do this:
It’s really the same thing only written a bit more compactly (it does make sure that
$resultis always defined though). I would definitely not recommend trying to make the code slightly shorter at the cost of making it much harder to read.If you had an unknown or known but large number of variables to process then there would be better solutions. But for just two, hardcoding like this is fine.