Auto increment in php

Hello Guys, I am doing auto increment no# in php with below code.

Its giving me the result 001,002,003,…010,

for($i = 1; $i <= 10; $i++) {
       $formattedNumber = sprintf('%03d', $i);
       echo "$formattedNumber,";
    }

I like to get the output like 100,101,102…110.
Is there anyway to do this?

start with 100 and not with 1.

1 Like

If I start with 100 , it doesn’t give me any output.

php.net/for

Do you also change

$i <= 10
1 Like

you shouldn’t end with 10 then, obviously.

1 Like

Thank you all.

Here again…I have got the autoincrement process. Now I want to convert the autoincremnet value in to an array. I did below but result is not okay.

I’m getting the below output
Array ( [0] => 110 )

But it should be as below.
Array ( [0] => 100 [1] => 101 [2] => 102 [3] => 103 [4] => 104 [5] => 105 [6] => 106 [7] => 107 [8] => 108 [9] => 109 [10] => 110 )

Expecting you guideline/comments to get the desired output. How to do the coding.

	for($i = 100; $i <= 110; $i++) {
       echo $formattedNumber = sprintf('%03d', $i);
    //$formattedNumber1="$formattedNumber,";
    }
	echo "</br>";
	$myarray=array ();
	$myarray[] = $formattedNumber;
			print_r($myarray);

Below is the output , when i run the code.

Look at your code again. Especially note what is inside the loop, and what is outside.

Please explain a bit more, I’m not getting it. Here below I change something but its not okay.

for($i = 100; $i <= 110; $i++) {
       echo $formattedNumber = sprintf('%03d', $i);
    
    }
	echo "</br>";
	$formattedNumber=array ();
	$formattedNumber[] = $formattedNumber;
			print_r($formattedNumber);

Output is,
Array ( [0] => Array ( ) )

Please look at your code again. Especially note what is inside the loop, and what is outside.

Do you by any chance happen to have a brother that uses a screen name of uniqueideaman? Your code seems familiar.

In any event:

$formattedNumbers = [];
for($i = 100; $i <= 110; $i++) {
   $formattedNumbers[] = sprintf('%03d', $i);
}
print_r($formattedNumbers);
3 Likes

Many thanks .

See the difference between this code and yours?
Initialization of the array before the loop.
Inserting array elements inside the loop.
Output of the result after the loop.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.