Join variables and add 0 to an 11-digit php field

-2

I am generating a bar code, it will have a base that will be as follows:

  • Store number: $v_ficha_loja = $row['ficha_loja']; = (1) or (2) etc ..

  • Environment number: $v_ficha_ambiente = $row['ficha_ambiente']; (1) or (2) etc ..

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

Well, I'm generating a report and every report will have its barcode, you doubt:   

Based on above the bar code will have 11 numbers, as follows:

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

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

I already have the system code and bar code all ready, I just need to generate that number.

Intended end result:

  

01010000001

    
asked by anonymous 19.08.2016 / 20:42

2 answers

5

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

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
    
19.08.2016 / 21:00
5

sprintf ()

sprintf is a very handy alternative to format your string :

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

See working at IDEONE .

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

The syntax is the same as the printf mentioned by Pope Charlie, but since you are going to generate bars, 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 is the value, followed by the number of houses, of 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 at IDEONE .

More details on PHP manual .


substr ()

This alternative is just to show you ways to work with strings in PHP. I put 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 at IDEONE .

More details on PHP manual .

    
20.08.2016 / 02:52