# Combining strings

4 replies to this topic

### #1 oracle259

oracle259
• Members
• 119 posts

Posted 08 October 2006 - 04:09 AM

how do i achieve the following.

say i have
\$string1 = "12345";
\$string2 = "54321";

how do i go about combining them to get

\$string3 = "1524334251";

thanks

### #2 kenrbnsn

kenrbnsn
• Staff Alumni
• 8,235 posts
• LocationHillsborough, NJ, USA

Posted 08 October 2006 - 04:21 AM

Use the fact that you can treat strings like arrays:
```<?php
\$string1 = "12345";
\$string2 = "54321";
\$string3 = '';
for(\$i=0;\$i<strlen(\$string1);\$i++)
\$string3 .= \$string1[\$i] . \$string2[\$i];
echo \$string3;
?>```

Ken

### #3 oracle259

oracle259
• Members
• 119 posts

Posted 09 October 2006 - 01:48 AM

thanks for the tips. Im curious though is there a way to make combination random or somewhat random.

### #4 kenrbnsn

kenrbnsn
• Staff Alumni
• 8,235 posts
• LocationHillsborough, NJ, USA

Posted 09 October 2006 - 04:30 AM

Here's the same script with the addition of two real arrays to store the characters of the strings. Then I use the shuffle() function to randomize each array before combining them as before.
```<?php
\$string1 = "12345";
\$string2 = "54321";
\$string3 = '';
\$str1 = array();
\$str2 = array();
\$str3 = '';
for(\$i=0;\$i<strlen(\$string1);\$i++) {
\$str1[] = \$string1[\$i];
\$str2[] = \$string2[\$i];
\$string3 .= \$string1[\$i] . \$string2[\$i];
}
echo \$string3;
shuffle(\$str1);
shuffle(\$str2);
for (\$i=0;\$i<count(\$str1);\$i++)
\$str3 .= \$str1[\$i] . \$str2[\$i];
echo '<br>'.\$str3;
?>```

Ken

oracle259
• Members