PHP: print for loop index to data size dynamic by $i value

时间:2018-04-20 01:12:27

标签: php phpoffice

Please how can i achieve something like this:

A-FIRSTNAME
B-LASTNAME
C-MIDDLENAME
D-PHONE

her is my code

<php 

   $alphabet = range('A','D');
   for ($i = 1; $i<4; $i++){
      $i2 = $i;
      echo $alphabet[$i2]."-FIRSTNAME";
      echo $alphabet[$i2]."-LASTNAME";
      echo $alphabet[$i2]."-MIDDLENAME";
      echo $alphabet[$i2]."-PHONE";
      $i2++;
  }

?>

3 个答案:

答案 0 :(得分:0)

您可以这样做:

$arr = array('FIRSTNAME','LASTNAME','MIDDLENAME','PHONE');

$i = 0;
foreach (range('A', 'D') as $alphabet) {
    echo $alphabet .'-'. $arr[$i] . '\n';
    $i++;
}

答案 1 :(得分:0)

PHP&gt; 7:

<?php
$phrases = [
    'FIRSTNAME', 
    'LASTNAME', 
    'MIDDLENAME',
    'PHONE'
];
$chars  = range('A','Z');
foreach ($phrases as $index => $phrase) {
    echo ($chars[$index] ?? '?') . ' => ' . $phrase;
}

PHP&lt; 7:

<?php
$phrases = [
    'FIRSTNAME', 
    'LASTNAME', 
    'MIDDLENAME',
    'PHONE'
];
$chars  = range('A','Z');
foreach ($phrases as $index => $phrase) {
    echo (isset($chars[$index]) ? $chars[$index] : '?') . ' => ' . $phrase;
}

答案 2 :(得分:0)

<?php 

   $alphabet = range('A','D');


   for ($i = 0; $i<4; $i++){

      echo nl2br($alphabet[$i]."-FIRSTNAME\n");
      echo nl2br($alphabet[$i]."-LASTNAME\n");
      echo nl2br($alphabet[$i]."-MIDDLENAME\n");
      echo nl2br($alphabet[$i]."-PHONE\n");
      echo nl2br("\n");
      echo nl2br("\n");
  }

?>