Jump to content

Archived

This topic is now archived and is closed to further replies.

oracle259

Combining strings

Recommended Posts

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

Share this post


Link to post
Share on other sites
Use the fact that you can treat strings like arrays:
[code]<?php
$string1 = "12345";
$string2 = "54321";
$string3 = '';
for($i=0;$i<strlen($string1);$i++)
  $string3 .= $string1[$i] . $string2[$i];
echo $string3;
?>[/code]

Ken

Share this post


Link to post
Share on other sites
thanks for the tips. Im curious though is there a way to make combination random or somewhat random.

Share this post


Link to post
Share on other sites
Here's the same script with the addition of two real arrays to store the characters of the strings. Then I use the [url=http://www.php.net/shuffle]shuffle()[/url] function to randomize each array before combining them as before.
[code]<?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;
?>[/code]

Ken

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.