0

I am trying to print out a series of strings in a loop, modifying the string each iteration. Specifically, I want to add a letter into the string and with each iteration sequentially increment the letter through the alphabet.

For example if I run the foreach function below:

foreach ( $terms as $term ) {
    echo "data-tax='".$term->name."'";
}

I would get something like

data-tax='apple'
data-tax='orange'
data-tax='banana'

However I want to add a letter into the string which increments each run yielding the following:

data-tax-a='apple'
data-tax-b='orange'
data-tax-c='banana'

How can I achieve this? I know I can add a letter into the string, but how can I move it through the alphabet?

AlienHoboken
  • 2,750
  • 20
  • 23
Vincent1989
  • 1,593
  • 2
  • 13
  • 25

2 Answers2

4

You can increment letters/strings in PHP like you would numbers. So just use a letter like you would a counter and increment it each loop. See also: Increment Letters like numbers

$letter = 'a';
foreach ( $terms as $term ) {
    echo "data-tax-{$letter}='".$term->name."'";
    $letter++;
}
Community
  • 1
  • 1
AlienHoboken
  • 2,750
  • 20
  • 23
1
$l = 'a';
foreach ( $terms as $term ) {
    $tName = $term->name;
    echo "data-tax-$l='$tName'";
    $l++;
}

Please note that incrementing from z will result in aa, i.e.:

$letter = "z";
$letter++;
echo($letter);
//aa
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268