0

I have an order form that uses the same name for each row item, an example below:

<input name="item['1']['stock_code']">
<input name="item['1']['quantity']">

<input name="item['2']['stock_code']">
<input name="item['2']['quantity']">

I am iterating over each of the $_POST item's like so:

$items = $_POST['item'];

foreach($items as $item){

    $item_stock_code = $item['stock_code'];
    $item_description = $item['description'];
    $item_price_net = $item['sale_price'];
    $item_quantity = $item['quantity'];
    $item_notes = $item['order_notes'];

}

However, I am now receiving an error when trying to access each property of an undefined index.

An example of print_r($item) is below:

Array
(
    ['stock_code'] => PLN-10002J
    ['quantity'] => 2
    ['description'] => 5MM-20MM TRANSFER CENTRE PUNCH (PLN-10002J)
    ['sale_price'] => 24.35
    ['order_notes'] => testt
)

Where am I going wrong, trying to access the values of each item?

5
  • What is the exact error message? Commented Aug 15, 2015 at 19:52
  • @u_mulder... Notice: Undefined index: stock_code is the error, along with the same for description, sale_price, quantity and order_notes. Commented Aug 15, 2015 at 19:53
  • Are you sure that error related to foreach loop? Commented Aug 15, 2015 at 19:54
  • @u_mulder... Yes, the line it says the error is on ties up with the foreach loop Commented Aug 15, 2015 at 19:54
  • @mario... Can you please submit that as an answer please? Removing the single quotes has resolved the issue. Commented Aug 15, 2015 at 20:02

1 Answer 1

2

If your form names contain single quotes around the keys like that:

<input name="item['1']['stock_code']">
<input name="item['1']['quantity']">

Then PHP will retain them as literal array keys, including the quotes.
So you had to access entries with:

#              ↓        ↓
$_POST["'1'"]["'stock_id'"]
// Notice the double/single quote combos.

So, yes, it's best to remove the ' quotes from the the form field names=, so PHP constructs standard array keys.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.