Scott Saunders
Scott Saunders

Reputation: 30414

Loop through an array of data and print an 'incrementing' letter

I need to loop through an array of data and print an 'incrementing' letter for each array value. I know I can do this:

$array = array(11, 33, 44, 98, 1, 3, 2, 9, 66, 21, 45); // array to loop through
$letters = array('a', 'b', 'c', ...); // array of letters to access
$i = 0;
foreach($array as $value) {
    echo $letters[$i++] . " - $value";
}

It seems that there should be a better way than having to create an alphabet array. Any suggestions?

Note - My loop will never get through the entire alphabet, so I'm not concerned about running out of letters.

Upvotes: 11

Views: 2953

Answers (8)

BrettAHale
BrettAHale

Reputation: 800

To add for fun...

$array = array(11, 33, 44, 98, 1, 3, 2, 9, 66, 21, 45);
$new_array = array_combine(array_slice(range('a','z'),0,count($array)),$array);
    foreach($new_array as $k=>$v){
        echo "$k - $v";
    }

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382806

Use the range function:

$letters = range('a', 'z');
print_r($letters);

You can also use foreach loop to take on each letter individually:

foreach($letters as $letter) {
    echo $letter . '<br />';
}

Upvotes: 23

Peter Ajtai
Peter Ajtai

Reputation: 57695

I realize you already accepted and answer, but I believe this is what you're looking for:

Simple use of the increment operator:

<?php
$array = array("cat","car","far","tar","tag");

  // No need for an array, just set $letter to "a", then increment it.
$letter = "a";

foreach($array as $value) {
      // Print your letter, then increment it.
    echo $letter++ . " - $value\n";
}
?>

Look at it live.

The big advantage of using this method over creating an array is that you don't need to worry about running out of letters, since you just move into double letters: like this.

Upvotes: 4

Mark Baker
Mark Baker

Reputation: 212452

Just as a demonstration (I know you've already accepted an answer), but it's sometimes useful to know that you can also increment character variables:

$var = 'a';
do {
   echo $var++.'<br />';
} while ($var != 'aa');

Upvotes: 8

JohnFx
JohnFx

Reputation: 34909

for ($counter = ord('a'); $counter <= ord('z'); $counter += 1) {
    echo chr($counter) . " - $counter";
}

Upvotes: 3

tplaner
tplaner

Reputation: 8461

You won't have to have an iterator if you make use of the $key => $value functionality of a foreach loop:

$letters = range('a', 'z');

foreach($letters as $key => $value)
{
    echo $key . '=>' . $value;
}

You could even go as far as to simply do:

foreach(range('a', 'z') as $key => $value)
{
    echo $key . '=>' . $value;
}

Upvotes: 0

CrayonViolent
CrayonViolent

Reputation: 32517

$letters = range('a','z');

Upvotes: 20

Thomas Langston
Thomas Langston

Reputation: 3735

Did you mean to have something that looked like this?

foreach(range('a','z') as $value)
{
  echo $value . ","
}

Upvotes: 3

Related Questions