HI below example show <?php $colors = array("red","green","blue","yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?> PHP: out is red green blue yellow Code (markup): But my out put requirements is 1-red 2-green 3-blue 4-yellow Code (markup):
You can simply do as this: <?php $colors = array("red","green","blue","yellow"); foreach ($colors as $key => $value) { echo ($key+1).' - '.$value.'<br>'; } ?> PHP:
Tested, and worked: <?php $colors = array("red","green","blue","yellow"); $i = 1; foreach ($colors as $value) { echo "$i-$value <br>"; $i++; } ?> PHP:
... and slow as molassas compared to @PoPSiCLe's version -- though I'd suggest using comma delimits instead of string addition since it's more predictable a result and a fraction faster. I'd probably also stop supporting PHP 5.3/lower and drop the whole 'array' keyword nonsense (NEVER liked that), and get rid of the stupid malfing slower double quotes while at it. $colors = ['red', 'green', 'blue', 'yellow']; foreach ($colors as $key => $value) echo $key + 1, ' - ', $value, '<br />'; Code (markup): Though if the relationship isn't fixed and you don't need that exact formatting, I'd consider making that a LIST. You know, semantic markup and such. $colors = ['red', 'green', 'blue', 'yellow']; echo ' <ol>'; foreach ($colors as $value) echo '<li>', $value, '</li>'; echo ' </ol>'; Code (markup): After all, that's what OL are FOR!
Can I just ask why two people now have added a counter-variable? It's _completely_ unnecessesary in PHP - an array is already keyed, even though the keys aren't defined. Hence, there are no reason to add another counter, when a simple arithmetic operator (+1) on the existing key works just fine. I do however agree with most of what @deathshadow said, apart from the skipping of any PHP-version below 5.3 - a lot of hosts still use PHP 5.3 and won't be upgrading for a while yet - and yes, of course you can switch providers etc., but that's not always an option.
Any provider that can't be bothered to keep up to date on the server software, therein missing security improvements... isn't worth using in the first place. Land sakes that's now TWO revisions behind.... It's like the jack-holes who ran 4.5 side by side with 5.x because developers couldn't be bothered to update their software to not throw endless errors and warnings; IMHO a good sign you shouldn't work with such developers. Of course, SO looking forward to people running around like chickens with their heads cut off when 6 drops; of course you'll have the same nonsense of trying to run 5 and 6 side by side as last time.