I have an associative array. Two dimensions which I am iterating through like this
foreach ( $order_information as $sector_index => $sector_value ){
echo 'sector : ' . current($order_information) ;
echo '<br>';
foreach ( $sector_value as $line_index => $line_value ){
}
}
The current() is an attempt to get the iteration the loop is in. It seems like this should give me that. However, elsewhere on that page there is the suggestions that you just do like
$index = 0
foreach ( $array as $key => $val ) {
echo $index;
$index++;
}
I wonder if I am using current incorrectly, as echo 'sector : ' . current($order_information); just prints sector : Array
Is $index++ bad syntax? Is there a better way to do this?
Answer
As far as I know there is no build in numeric counter in a
foreachloop in PHP.So you need your own counter variable. Your example code looks quite good to do that.
By the way,
$index++;is fine.Example
Here is an example illustrating which variable stores which value.
The output will be that.
Current-Function
I think you misunderstood
current($array). It gives you the value pointed by an internal array pointer, which can be moved usingnext($array),prev($array)andend($array).Take a look at the manual to make thinks clear.