Add $x in to $v every 10 charature. ($x changes every time)

Add $x in to $v every 10 charature. ($x changes every time)
LVL 5
mnb93Asked:
Who is Participating?
 
BogoJokerConnect With a Mentor Commented:
Correction: while loop should be: while ($length >= 10)

Also if you wanted you could combine three lines into one with a for loop.
$length = strlen($x);
while ($length >= 10)
$length -= 10;

All into:
for ($length = strlen($x); $length >= 10; $length -= 10)

Joe P
0
 
BogoJokerCommented:
Hi mnb93,

I don't understand what you want.

Joe P
0
 
mnb93Author Commented:
dw I worked out what I needed.
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
mnb93Author Commented:
$d = '';
for($i=0;$i<strlen($x);$i++)
{
    if($i%10 == 0 AND $i !== 0)
    {
        //addchar
        $d .= $s.substr($x, $i, 1);
        $s = mkNews();
    }
    else
    {
        //do nothing
        $d .= substr($x, $i, 1);
    }
}

Points will go to anyone who can make something faster than that.
0
 
BogoJokerCommented:
You could do:
if (strlen != 0)
{
    for($i=1;$i<strlen($x);$i++)
    {
        if($i%10 == 0)
        {
            //addchar
            $d .= $s.substr($x, $i, 1);
            $s = mkNews();
        }
        else
        {
            //do nothing
            $d .= substr($x, $i, 1);
        }
    }
}

This, although it looks larger eliminiates the check if i = 0 every single time.  It starts at 1 checking that the strlen() is in fact greater then 0.
Also let me write another one.
0
 
BogoJokerCommented:
$length = strlen($x);
$pos = 0;
while($length > 10)
{
  $d .= substr($x, $pos, 9);
  $d .= $s.substr($x, $i, 1);
  $s = mkNews();
  $pos += 10;
  $length -= 10;
}
$d  .= substr($x, $pos);


This versino actually goes 10 letters at a time.  Works for $x string of any size it takes the 10 letters like so:
Add 9 to $d
Add $s and the 10th
Call mkNews()

Until there are less then 10 letters left to add, just add them onto the end.
Much faster cause your not looping letter by letter, your taking them 10 at a time.

Joe P
0
 
RoonaanConnect With a Mentor Commented:
What about:

$d =  preg_replace('/(.{10})/e', '"\0".mkNews()', $x);

-r-
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.