Adding leading 0 in php

20,904

Solution 1

If it is coming from a DB, this is the way to do it on a sql query:

lpad(yourfield, (select length(max(yourfield)) FROM yourtable),'0') yourfield

This is will get the max value in the table and place the leading zeros.

If it's hardcoded (PHP), use str_pad()

str_pad($yourvar, $numberofzeros, "0", STR_PAD_LEFT);

This is a small example of what I did on a online php compiler, and it works...

$string = "Tutorial 1 how to";

$number = explode(" ", $string); //Divides the string in a array
$number = $number[1]; //The number is in the position 1 in the array, so this will be number variable

$str = ""; //The final number
if($number<10) $str .= "0"; //If the number is below 10, it will add a leading zero
$str .= $number; //Then, add the number

$string = str_replace($number, $str, $string); //Then, replace the old number with the new one on the string

echo $string;

Solution 2

str_pad()

echo str_pad($input, 2, "0", STR_PAD_LEFT);

sprintf()

echo sprintf("%02d", $input);
Share:
20,904
msjsam
Author by

msjsam

Updated on July 09, 2022

Comments

  • msjsam
    msjsam almost 2 years

    I have

    • tutorial 1 how to make this
    • tutorial 21 how to make this
    • tutorial 2 how to make this
    • tutorial 3 how to make this

    and i need

    • tutorial 01 how to make this
    • tutorial 21 how to make this
    • tutorial 02 how to make this
    • tutorial 03 how to make this

    so i can order them properly. (adding leading 0 when single digit is found)

    What would be a php method to convert?

    thanks in advance

    note-please make sure that it identifies the single digit numbers only first and then add the leading zero

    • Musa
      Musa almost 12 years
    • Peter
      Peter almost 12 years
      What about three digit numbers? When you reach 100 tutorials, would you like 01 to become 001? What about four digit numbers? etc.
    • msjsam
      msjsam almost 12 years
      for now, two digits are good, i don't see a case where the tutorial is more than 100, thank you
  • msjsam
    msjsam almost 12 years
    this one is not picking up the condition "single digits only" please help