Oscar
Oscar

Reputation: 1103

How to display string number which is start from zero?

what I want to do is add the number in loop and get the result, my addition is correct, but the string was not correct.

here is my code:

$contract_records->start_no = 0;
for($i=1;$i<=($contract_records->no_of_pages);$i++){            
$start_no = $contract_records->start_no;        
$total = $start_no + $i;
var_dump($total);

var_dump result is:

int(1) int(2) int(3) int(4) int(5)

what I want in my result is:

00001
00002
00003
00004
00005

detail:

$contract_records->start_no = 00001
$contract_records->no_of_pages = 5

any idea? thanks

Upvotes: 0

Views: 2894

Answers (3)

Martin Samson
Martin Samson

Reputation: 4090

Use sprintf:

sprintf("%05d", $i);

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

Upvotes: 4

deceze
deceze

Reputation: 522382

Numbers don't have a format. A numeric value is just the value, there are no leading zeros. Format your numbers upon output, for example using number_format or sprintf.

Upvotes: 3

Paul
Paul

Reputation: 141877

Use str_pad:

for($i = 1; $i <= 5; $i++)
    echo str_pad($i, 5, '0', STR_PAD_LEFT) . PHP_EOL; 

// Outputs:
// 00001
// 00002
// 00003
// 00004
// 00005

Upvotes: 1

Related Questions