Incrementing Numbers Starting from 0000 in PHP

Incrementing numbers starting from 0000 in php

$n2 = str_pad($n + 1, 5, 0, STR_PAD_LEFT);

Use str_pad() by adding 0s (third parameter) to the left (fourth parameter) of the old number $n incremented by 1 (first parameter) until the length is 5 (second parameter).

How to increment a value with leading zeroes using php

use str_pad()

$val = 1;
echo str_pad($val,4,"0",STR_PAD_LEFT); // 0001

$val = 10;
echo str_pad($val,4,"0",STR_PAD_LEFT); // 0010

increment number starting 0000

You have to add the zeros when converting the number back to a string:

 function incrementValue() {
var value = parseInt(document.getElementById('id').value, 10);
value = value || 0;
value++;
document.getElementById('id').value = ("00000" + value).substr(-5);
}

Formatting a number with leading zeros in PHP

Use sprintf :

sprintf('%08d', 1234567);

Alternatively you can also use str_pad:

str_pad($value, 8, '0', STR_PAD_LEFT);

Generate incremental id of numbers, Upper and Lower letters

Using 0,1-9, a-z and A-Z is "Base 62". Converting from base 10, to base 62 is very easy in PHP.

<?php
echo base_convert(10123, 10,26), "\n";
// outputs: 'ep9'
echo base_convert('ep9', 26, 10), "\n";
// output 10123

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

You can use sprintf: http://php.net/manual/en/function.sprintf.php

<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>

It will only add the zero if it's less than the required number of characters.

Edit: As pointed out by @FelipeAls:

When working with numbers, you should use %d (rather than %s), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.

For example:

sprintf("%04s", 10); returns 0010

sprintf("%04s", -10); returns 0-10

Where as:

sprintf("%04d", 10); returns 0010

sprintf("%04d", -10); returns -010

PHP - Increment a value

You are making a big mistake here. 000 in code is an octal number. Any literal number starting with a 0 in many programming languages is considered an octal literal. If you want to store 000, you need a string, not a number.

$start_value = "000";
while((int) $start_value /*--apply condition --*/) {
do something;
$start_value = str_pad((int) $start_value+1, 3 ,"0",STR_PAD_LEFT);
}


Related Topics



Leave a reply



Submit