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

Issue

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;
?>

Solution

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

?>

Answered By – icecub

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *