How can I return zero in front of other numbers?

Asked

Viewed 457 times

3

I have a record in my Mysql BD, example: A0001 and I need to take this value and go adding example A0001 + 1 = A0002.

I did the following:

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

echo $soma;

The return was A2, but I’d like you to stay A0002.

3 answers

4

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

$formatado = 'A'. str_pad($soma, 4, 0, STR_PAD_LEFT);
echo $formatado;

4


I could do the following using the 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;

2

Utilize str_pad, to set zeros to the left and then concatenate the A again, example:

<?php

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

Watch it run ONLINE

Browser other questions tagged

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