3

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?

Community
  • 1
  • 1
1252748
  • 14,597
  • 32
  • 109
  • 229
  • 1
    `current()` gives you the element pointed by the array's internal pointer. It will **not** give you an index. The proper way to do this is to use a counter, like you're doing in your second example. No, there's nothing wrong with `$index++`. It would also help if you could post how this `$order_information` array actually looks like. – NullUserException Nov 21 '12 at 20:51
  • No `$index++` is not bad syntax it is a shorter way of saying `$index = $index + 1`. – Jared Nov 21 '12 at 20:53

1 Answers1

4

Answer

As far as I know there is no build in numeric counter in a foreach loop in PHP.

So you need your own counter variable. Your example code looks quite good to do that.

$index = 0;
foreach($array as $key => $val) {
    $index++;
}

By the way, $index++; is fine.

Example

Here is an example illustrating which variable stores which value.

$array = array(
    "first"  => 100,
    "secnd" => 200,
    "third"  => 300,
);

$index = 0;
foreach($array as $key => $val) {
    echo "index: " . $index . ", ";
    echo "key: "   . $key   . ", ";
    echo "value: " . $val   . "\n";
    $index++;
}

The output will be that.

index: 0, key: first, value: 100
index: 1, key: secnd, value: 200
index: 2, key: third, value: 300

Current-Function

I think you misunderstood current($array). It gives you the value pointed by an internal array pointer, which can be moved using next($array), prev($array) and end($array).

Take a look at the manual to make thinks clear.

danijar
  • 32,406
  • 45
  • 166
  • 297