Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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.

like image 823
Scott Saunders Avatar asked Aug 04 '10 17:08

Scott Saunders


People also ask

How do you increment the value of an array?

To increment a value in an array, you can use the addition assignment (+=) operator, e.g. arr[0] += 1 . The operator adds the value of the right operand to the array element at the specific index and assigns the result to the element.

How do you iterate through an array in a for loop?

Iterating over an array You can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.

Can you loop an array?

The Basic For Loop JavaScript arrays are zero based, which means the first item is referenced with an index of 0. As you can see the for loop statement uses three expressions: the initialization, the condition, and the final expression. The final expression is executed at the end of each loop execution.

Which loop is used to iterate over arrays and strings?

The for..of loop in JavaScript allows you to iterate over iterable objects (arrays, sets, maps, strings etc).


4 Answers

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 />';
}
like image 170
Sarfraz Avatar answered Sep 29 '22 11:09

Sarfraz


$letters = range('a','z');
like image 40
Crayon Violent Avatar answered Sep 29 '22 13:09

Crayon Violent


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');
like image 45
Mark Baker Avatar answered Sep 29 '22 11:09

Mark Baker


Did you mean to have something that looked like this?

foreach(range('a','z') as $value)
{
  echo $value . ","
}
like image 44
Thomas Langston Avatar answered Sep 29 '22 11:09

Thomas Langston