jhui
jhui

Reputation: 77

Iterating through a Foreach loop

I want to iterate a number in this foreach so something like 'item_name_' . $i... But I can't work out how to do it? Can you give me a hand?

  $cart = $this->cart->contents();
  foreach ($cart as $item){
      $this->paypal_lib->add_field('item_name_1', $item['name']);
      $this->paypal_lib->add_field('amount_1', $item['subtotal']);
      $this->paypal_lib->add_field('item_number_1', $item['id']);
      $this->paypal_lib->add_field('quantity_1', '1');
  }

Upvotes: 0

Views: 154

Answers (1)

David Thomas
David Thomas

Reputation: 253308

  // initialise variable:
  $i = 0;

  $cart = $this->cart->contents();
  foreach ($cart as $item){
      $i++;
      // do what you want with the counter variable '$i'.

      $this->paypal_lib->add_field("item_name_$i", $item['name']);
      $this->paypal_lib->add_field("amount_$i", $item['subtotal']);
      $this->paypal_lib->add_field("item_number_$i", $item['id']);
      $this->paypal_lib->add_field("quantity_$i", '1');
  }

Upvotes: 7

Related Questions