0

I have a two variable one is string contains number and another one is number, I want increase the numeric part of string upto second number.

$n ='sh500';
$c = 3; 
for($i=$n;$i<$c;$i++)
echo $i.'<br>';  

I want output like:

sh500
sh501
sh502

7 Answers 7

5

Use $n++ where $n = 'sh500'. It works.

$n ='sh500';
$c = 3; 
for($i = 0;$i < $c;$i++) {
    echo $n++.'<br>';
}

Will output

sh500 <br>
sh501 <br>
sh502 <br>

It even works when ending with a alphanumeric character, because php converts it to the ASCII value of the character and adds one so a will become b and so on. But that's out of the scope of the question :)

Sign up to request clarification or add additional context in comments.

Comments

2
$x="sh500";
$x = substr($x,0,2) . (substr($x,2) + 1);

echo $x;

echoes sh501 (works for any string having a number from 3rd character)

Comments

1
$n = 'sh';
for($i = 500; $i < 503; $i++) {
    echo "$n$i\n";
}

3 Comments

$n ='sh500'; is not fixed,it change dynamicaly like $n ='dewd94' or $n='rew231' etc.
then place this code in function and just pass the dynamic number to the function and use it to initialize $i (can also pass the upper limit then)
@er_Rajendraa: then you can start out by splitting the text from the numeric part using preg_match.
0
$n="sh50";
for($i=0;$i<10;$i++){
$j=$n.$i;

echo $j."<br>";
}

it echo: sh500 sh501 sh502 sh503 sh504 sh505 sh506 sh507 sh508 sh509

Comments

0
$n = 'sh500';
$c = 3;
$sh = substr($n,0,2); // will be "sh"
$number = substr($n,2,5) + 1; // will be "500"
for($i = $number; $i < 504; $i++) {
 echo $sh.$i."\n";
}

Live demo: Here

Comments

0

if it is always a string of length 2 else use preg_match to find the first occurrence of a number. http://www.php.net/manual/en/function.preg-match.php

$number = intval(substr($n, 2));
$number++;

echo substr($n, 0, 2) . $number;

Comments

0
$x = "sh500";
$s = substr($x, 0, 2);
$n = substr($x, 2);

$c = 3; 
for ($i = $n; $i < ($n + $c); $i++)
{
    echo $s.$i.'<br>';
}

OR another simple way is...

$n ='sh500';
$c = 3; 
for ($i = 0; $i < $c; $i++) {
    echo $n++."<br>";
}

Output

sh500
sh501
sh502

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.