I have a PHP problem where I have a string of numbers:
ie/ 1,2,3,4,5,6,7,8,9...... X
I know the first number and have to create a string X long so that it wraps around
for example if my string is 1,2,3,4,5 and my first number is 4 - i need to return the string:
4,5,1,2,3
I'd like to create a function to achieve this - any help would be great!
Thanks.
<?php
function MyWrap($string, $first)
{
$splitHere = strpos($string, $first);
return rtrim(substr($string, $splitHere).','.substr($string, 0, $splitHere), ',');
}
echo MyWrap('1,2,3,4,5', '4');
?>
Output:
4,5,1,2,3
$pos = strpos($string,$first_number);
return substr($s,$pos).','.substr($s,0,$pos);
function wrapAroundNeedle($myString, $myNeedle)
{
$index = strrpos($myString, $myNeedle);
return substr($myString, $index).",".substr($myString, 0, $index - 1);
}
How to roll your own. Note that strrpos only allows single characters for $needle in php 4.
string substr ( string $string , int $start [, int $length ] )
int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )
I believe I understand what you need - try this:
function numsWrap($firstNumber, $total) {
$newStr = "";
$inc = $firstNumber;
for($i = 0; $i < $total+1; $i++) {
if($i == 0) {
$newStr .= $inc;
} else {
if($inc == $total) {
$newStr .= "," . $inc;
$inc = 0;
} else {
$newStr .= "," . $inc;
}
}
$inc++;
}
return $newStr;
}
Usage:
echo numsWrap(5, 10);
5,6,7,8,9,10,1,2,3,4,5