How to write a program to concatenate two strings character by character. e.g : JOHN + SMITH = JSOMHINTH

Viewed 3714

This is my code but it only gives results if both strings are of same length. But what if I want to compare strings of different lengths?

<?php

  $n1 = "Apple";
  $n2 = "Orang";

  //count length fo both string 
  $count1 = strlen($n1);
  $count2 = strlen($n2);
  $finalcount = 0;

  if($count1 > $count2) {
    $finalcount = $count1;
  } elseif ($count1 < $count2) {
    $finalcount = $count2;
  } else {
    $finalcount = $count1;
  }

  //convert string to array
  $n1 = str_split($n1);
  $n2 = str_split($n2);

  $i = 0;
  $result = "";
  for($i = 0;$i < $finalcount  ; $i++) {
    $result = $result .$n1[$i] . $n2[$i];
  }

  echo $result;
?>
3 Answers

Here is exactly what you are looking for: PHP - Merge two strings

/**
 * Merges two strings in a way that a pattern like ABABAB will be
 * the result.
 *
 * @param     string    $str1   String A
 * @param     string    $str2   String B
 * @return    string    Merged string
 */  
function MergeBetween($str1, $str2){

    // Split both strings
    $str1 = str_split($str1, 1);
    $str2 = str_split($str2, 1);

    // Swap variables if string 1 is larger than string 2
    if (count($str1) >= count($str2))
        list($str1, $str2) = array($str2, $str1);

    // Append the shorter string to the longer string
    for($x=0; $x < count($str1); $x++)
        $str2[$x] .= $str1[$x];

    return implode('', $str2);
}

This would be one way to do it (some explanation in the comments):

<?php

$str = 'test';
$str2 = 'test2';

$arr = str_split($str);
$arr2 = str_split($str2);

// Find the longest string
$max = max(array(strlen($str), strlen($str2)));

$result = '';

for($i = 0; $i < $max; $i++){
    // Check if array key exists. If so, add it to result
    if (array_key_exists($i, $arr)){
        $result .= $arr[$i];
    }

    if (array_key_exists($i, $arr2)){
        $result .= $arr2[$i];
    }
}

echo $result; //tteesstt2

?>
<?php 

// Write a program to concatenate two strings character by 
// character. e.g : JOHN + SMITH  = JSOMHINTH

echo "\nstring 1 : ".$string1="JOHN";
echo "\nstring 2 : ".$string2="SMITH";

$firstArray=str_split($string1);
$secondArray=str_split($string2);

if(count($firstArray)>count($secondArray)) {
  $loop=count($firstArray);
}
else {
  $loop=count($secondArray);
}

$result=[];
$i=0;
while($i<$loop) {
  isset($firstArray[$i])?array_push($result,$firstArray[$i]):'';
  isset($secondArray[$i])?array_push($result,$secondArray[$i]):'';
  $i++;
}
echo "\nResult String : ".implode($result);

?>
Related