Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP Have a "built-in" iterator in a Foreach loop?

I'm using a foreach loop to go through the REQUEST array, as I want to have an easy way to utilize the REQUEST array's keys and values.

However, I also want to have a numerical index of how many times the loop has run, as I'm writing a spreadsheet with PHPExcel, and I want to use the SetCellValue function. I'm thinking something like this:

foreach( $_REQUEST as $key => $value){
    $prettyKeys = ucwords(preg_replace($patt_underscore," ",preg_replace($patt_CC,"_",$key)));
    $prettyVals = ucwords(preg_replace($patt_underscore," ",preg_replace($patt_CC,"_",$value)));
    // Replace CamelCase with Underscores, then replace the underscores with spaces and then capitalize string
    // "example_badUsageOfWhatever" ==> "Example Bad Usage Of Whatever"


    $myExcelSheet->getActiveSheet()->SetCellValue( "A". $built-in-foreach-loop-numerical-index ,$prettyKeys);
    $myExcelSheet->getActiveSheet()->SetCellValue( "B". $built-in-foreach-loop-numerical-index ,$prettyVals);
}

I know I can easily implement something like $c = 0 outsite the foreach and then just increment it each time the loop is run, but is there something cleaner?

like image 560
Goldentoa11 Avatar asked Aug 13 '12 14:08

Goldentoa11


People also ask

How does PHP foreach loop work?

PHP foreach loop is utilized for looping through the values of an array. It loops over the array, and each value for the fresh array element is assigned to value, and the array pointer is progressed by one to go the following element in the array.

What are iterators in PHP?

An iterable is any value which can be looped through with a foreach() loop. The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a data type for function arguments and function return values.

Does PHP have foreach?

PHP provides you with the foreach statement that allows you to iterate over elements of an array, either an indexed array or an associative array. The foreach statement iterates over all elements in an array, one at a time. It starts with the first element and ends with the last one.


1 Answers

PHP's foreach does not have this functionality built in (per the manual). Use a for loop to have an iterator or implement it yourself.

like image 144
nwalke Avatar answered Sep 16 '22 14:09

nwalke