1

I have a for loop like this in php

<?php
for($i=0;$i<=100;$i++)
{
echo $i;
}

What I need is, I want to generate roll number using this for loop like this.

SN0001  
SN0002  
SN0003  
.....  
SN0010  not SN00010
......  
SN0100  not SN000100

I have tried this

  <?php
  for($i=0;$i<=100;$i++) {
  $str='SN00'.$i;
  echo $str;
  }
  ?>

Note this (SN0010 and SN0100). I need SN0010,SN0100 not SN00010, SN000100.

What should I do for that?

2
  • Have you tried anything? Commented Mar 2, 2015 at 7:09
  • I dont know how to do that? That's why asking. Commented Mar 2, 2015 at 7:13

4 Answers 4

3

You can use str_pad() function:

<?php
for($i=0;$i<=100;$i++) {
  echo 'SN' . str_pad($i, 4, STR_PAD_LEFT, '0');
}
?>
Sign up to request clarification or add additional context in comments.

Comments

2
Please try this code-

    for($i=0;$i<=100;$i++) {
      echo 'SN' .sprintf("%'.04d\n", $i);
    }

Comments

1
for($i=0;$i<=100;$i++)
{
    if($i<=9){      
        $zeroValue = '000';
    }
    elseif($i>9 && $i<=99){
        $zeroValue = '00';
    }
    elseif($i>99 && $i<=999){
        $zeroValue = '0';
    }
echo 'SN'.$zeroValue.$i.'<br>';
}

3 Comments

I think this php loop is exactly correct and simple to use.
well, max value of $i is 100, thus, $i <= 999 is somehow inaccurate (working though).
I have given a limitation. If a user try to more than this value.
1
  <?php
  for($i=0;$i<=100;$i++) {
  $str='SN00'.$i;
  if(strlen($str)<6)
  {
    $str='SN000'.$i;
  }
  if(strlen($str)>6)
  {
    $str='SN0'.$i;
  }
  echo $str;
  }
  ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.