Append to beginning of string until length = x
I'm trying to开发者_JAVA百科 write a loop that appends a number to the beginning of a string until it is 15 characters long. What am I missing?
$i = rand(1,9);
while (strlen($fileNameNS > 15)){
$file13 = $i . $i . $fileNameNS;
}
$i++;
In each iteration of the loop, you modify $file13
, but your loop is only looking at $fileNameNS
, which never changes! Since it never changes, if the loop condition is initially true, it will always be true, and never exit.
Perhaps you meant this:
$fileNameNS = $i . $i . $fileNameNS;
Your condition is mixed up as well, in two ways.
- You're continuing while the length is greater than the intended length, when you should be continuing while the length is less than the intended length.
- You're applying
strlen
to the comparison$fileNameNS > 15
, when you should be applying the comparison to the value ofstrlen($fileNameNS)
.
while(strlen($fileNameNS) < 15) {
Note that because you're adding two copies of $i
at a time your final length may be 15 or 16. If this isn't what you want, you should be this instead:
$fileNameNS = $i . $fileNameNS;
You incrementing $i
with $i++
after the loop is finished, so inside the loop the value of $i
will never change. If you mean to increment $i
each iteration, so that different digits are prepended each time, you need to move that up one line, inside the loop. However if you do this then $i
could end up being longer than one digit, again raising the possibility of the final length being 16.
Already exists a function to do that:
http://php.net/manual/en/function.str-pad.php
As I see on your loop, don't need rand number each time, so str_pad fits well.
Also your while statement is incorrect.
while (strlen($fileNameNS) < 15)
You want it to act while the strlen is less than 15
You also don't need to increment $i
outside of the loop. And in fact may want to move your random number generator inside the loop. to have it be a random string of numbers.
for ($i = 0, $str = ''; $i < 15; $i++) {
$str .= rand(1, 9);
}
$i = rand(1,9);
$file13 = $fileNameNS;
while (strlen($file13) <= 15){
$file13 = $i . $i . $fileNameNS;
$i++;
}
精彩评论