Merge variables and include 0 to an 11 digit php field

Asked

Viewed 59 times

-2

I’m generating a bar code,:

  • Number of the shop: $v_ficha_loja = $row['ficha_loja']; = (1)or (2)etc..

  • Number of the environment: $v_ficha_ambiente = $row['ficha_ambiente']; (1)or (2)etc..

  • And a sequential number: 1,2,3,4,5,6,7, .... 100.

'Cause I’m generating a report and every report will have its barcode, doubt:

Based above the barcode will have 11 numbers, as follows:

  • x1x2xxxxxx1
  • x1x1xxxxxx2
  • x1x2xxxxxx3
  • x1x2xxxxxx4
  • x1x2xxxxx10
  • x1x2xxxxx11
  • x1x2xxxxx12
  • x1x2xxxx100

Where did I put it x I want to include the 0 how can I do this ?

I’ve got the system code and the barcode all ready,.

Intended end result:

01010000001

  • 0(Numero da loja)0(Numero do ambiente)0000(numero sequencial), would that be the sequence of numbers? The first 2 zeroes are mutable, or whole x will always be zero?

  • What you’ve tried to do?

2 answers

5


If the store number and the environment number are ALWAYS preceded by zero, you can use str_pad to create the repetition of zeros.

str_pad( 1   , 11 , '0' , STR_PAD_LEFT ) // 00000000001
str_pad( 10  , 11 , '0' , STR_PAD_LEFT ) // 00000000010 
str_pad( 100 , 11 , '0' , STR_PAD_LEFT ) // 00000000100

echo '0102' . str_pad( 100 , 11 , '0' , STR_PAD_LEFT ) // 010200000000100

Example with printf

printf( '%s1%s2%011s' , 0 , 0 , 1   ); // 010200000000001
printf( '%s1%s2%011s' , 0 , 0 , 10  ); // 010200000000010
printf( '%s1%s2%011s' , 0 , 0 , 50  ); // 010200000000050
printf( '%s1%s2%011s' , 0 , 0 , 100 ); // 010200000000100

5

sprintf()

The sprintf is a very practical alternative to format your string:

$barra = sprintf( "%'02d%'02d%'07d", $v_ficha_loja, $v_ficha_loja, $v_sequencia );

See working on IDEONE.

  • % to indicate replacement.
  • ' to indicate which character to fill (so we use '0)
  • then the number of digits
  • at last d to indicate that it is an integer

The syntax is the same as printf mentioned by Pope Charlie, but as you will generate bars, and not the value on the screen, it makes more sense to store in string.

More details on PHP manual.


str_pad()

With str_pad you say what the value is, followed by the number of boxes, the fill character and on which side it should be added:

$barra = str_pad( $v_ficha_loja    , 2, '0', STR_PAD_LEFT )
        .str_pad( $v_ficha_ambiente, 2, '0', STR_PAD_LEFT )
        .str_pad( $v_sequencia     , 7, '0', STR_PAD_LEFT );

See working on IDEONE.

More details on PHP manual.


replace()

This alternative is just to show ways to work with strings in PHP. I posted more to illustrate and think outside the box:

    $barra = substr(      '00'.$v_ficha_loja    , -2 )
            .substr(      '00'.$v_ficha_ambiente, -2 )
            .substr( '0000000'.$v_sequencia     , -7 );

See working on IDEONE.

More details on PHP manual.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.