[php] PHP prepend leading zero before single digit number, on-the-fly

PHP - Is there a quick, on-the-fly method to test for a single character string, then prepend a leading zero?

Example:

$year = 11;
$month = 4;

$stamp = $year.add_single_zero_if_needed($month);  // Imaginary function

echo $stamp; // 1104

This question is related to php string numbers zero

The answer is


You can use str_pad for adding 0's

str_pad($month, 2, '0', STR_PAD_LEFT); 

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )


The universal tool for string formatting, sprintf:

$stamp = sprintf('%s%02s', $year, $month);

http://php.net/manual/en/function.sprintf.php


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python

Examples related to zero

JAVA How to remove trailing zeros from a double Check if bash variable equals 0 How to create a numeric vector of zero length in R How to remove rows with any zero value Remove/ truncate leading zeros by javascript/jquery PHP prepend leading zero before single digit number, on-the-fly Fastest way to zero out a 2d array in C? Nullable types: better way to check for null or zero in c#