Hugo
Hugo

Reputation: 504

Add leading zero only if exist with php

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 ?

Upvotes: 1

Views: 1076

Answers (4)

Michael Berkowski
Michael Berkowski

Reputation: 270609

You can cram a ternary operation into the str_pad() calls to substitute zero length if the var is empty, but it is a bit ugly. Inside each str_pad() call, the expression !empty($var) ? 6 : 0 will supply a padding length of 6 if the variable isn't empty or 0 if it is, resulting in no output for empty variables.

echo str_pad($var1, (!empty($var1) ? 6 : 0), '0', STR_PAD_LEFT ) . str_pad($var2, (!empty($var2) ? 6 : 0), '0', STR_PAD_LEFT);

$var1 = "ok";
$var2 = "";
// $var2 excluded
// 0000ok

Upvotes: 0

Miraage
Miraage

Reputation: 3464

echo str_pad( $var  ?: '', 6, '0', STR_PAD_LEFT ) 
   . str_pad( $var2 ?: '', 6, '0', STR_PAD_LEFT );

works?

Upvotes: 0

jco
jco

Reputation: 677

You could use ternary form. (condition) ? (true return value) : (false return value), which cleans up the code slightly. So your code becomes:

$test1 = ($var ? str_pad( $var, 6, '0', STR_PAD_LEFT ) : '');
$test1 .= ($var2 ? str_pad( $var2, 6, '0', STR_PAD_LEFT ) : '');
echo $test1;

Upvotes: 0

Jon
Jon

Reputation: 437336

Well, you could do this:

$result = "";
$result .= $var  ? str_pad( $var, 6, '0', STR_PAD_LEFT ) : null;
$result .= $var2 ? str_pad( $var2, 6, '0', STR_PAD_LEFT ) : null;

It's really the same thing only written a bit more compactly (it does make sure that $result is 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.

Upvotes: 1

Related Questions