我有这样的代码如何代码打印像这样?

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?

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'). "
"; // DAP
echo initials('AULIA ABRAR'). "
";            // AAB
echo initials('AULIA'). "
";                  // AUL

demo

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.