How can I return zero in front of other numbers? [duplicate]

3

I have a record in my BD MySQL, example: A0001 and I need to get this value and add example A0001 + 1 = A0002 .

I've done the following:

$texto = "A0001";
$novotexto = substr($texto, -4);
$soma = ($novotexto+1);

echo $soma;

Return was A2 , but I'd like it to be A0002 .

    
asked by anonymous 05.02.2018 / 14:15

3 answers

4

You could do the following by using str_pad

$texto = "A0001";
$novotexto = substr($texto, -4);

$tempIni = substr($texto, 0,1); //Guardar inicio na variavel

$soma = ($novotexto+1);

$resultado = $tempIni . str_pad($soma, 4, "0", STR_PAD_LEFT);
echo $resultado;
    
05.02.2018 / 14:23
4

If the size is fixed, use the str_pad() function to add variable number of zeros to the left being at most four digits and at the end you can concatenate the letter.

$formatado = 'A'. str_pad($soma, 4, 0, STR_PAD_LEFT);
echo $formatado;
    
05.02.2018 / 14:20
2

Use str_pad , to put leading zeros and then concatenate A again, example:

<?php

$texto = "A0001";
$novotexto = substr($texto, -4);
echo $soma = 'A'.str_pad(($novotexto+1), 4, '0', STR_PAD_LEFT);

Watch running ONLINE

    
05.02.2018 / 14:22