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.
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.
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.
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.
The for..of loop in JavaScript allows you to iterate over iterable objects (arrays, sets, maps, strings etc).
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 />';
}
$letters = range('a','z');
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');
Did you mean to have something that looked like this?
foreach(range('a','z') as $value)
{
echo $value . ","
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With