Devo Avidianto P
Devo Avidianto P

Reputation: 75

I have code like this How to code print like this?

input name: DEVO AVIDIANTO PRATAMA output: DAP if the input three word , appears DAP

input name: AULIA ABRAR output: AAB if the input two words, appears AAB

input name: AULIA output: AUL   if the input one word, appears AUL

<?php
$nama = $_POST['nama'];
$arr = explode(" ", $nama);
//var_dump($arr);die;
$jum_kata = count($arr);
//echo $jum_kata;die;
$singkatan = "";
if($jum_kata  == 1){
  //print_r($arr);
  foreach($arr as $kata)
  {
  echo substr($kata, 0,3);
  }
}else if($jum_kata == 2) {
  foreach ($arr as $kata) {
    echo  substr($kata,0,2);
  }
}else {

  foreach ($arr as $kata) {
    echo  substr($kata,0,1);
  }

}

?>

how to correct this code :

else if($jum_kata == 2) {
  foreach ($arr as $kata) {
    echo  substr($kata,0,2);
  }

to print AAB?

Upvotes: 1

Views: 85

Answers (2)

KIKO Software
KIKO Software

Reputation: 16688

You could do:

elseif ($jum_kata == 2) {
   echo substr($kata[0],0,1);
   echo substr($kata[1],0,2);
}

This will just get the first character of the first word, and then two characters from the next word.
You are returning two characters from each word which is why you get AUAB.

Upvotes: 1

splash58
splash58

Reputation: 26153

As a variant of another approach. Put each next string over the previous with one step shift. And then slice the start of a resulting string

function initials($str, $length=3) {
  $string = '';
  foreach(explode(' ', $str) as $k=>$v) {
    $string = substr($string, 0, $k) . $v;
  }  
  return substr($string, 0, $length);
}

echo initials('DEVO AVIDIANTO PRATAMA'). "\n"; // DAP
echo initials('AULIA ABRAR'). "\n";            // AAB
echo initials('AULIA'). "\n";                  // AUL

demo

Upvotes: 3

Related Questions