The numbers on the end of each $_POST variable name represent different items. (The variables above would define 3 attributes about 2 different items.)

There is no variable which defines how many items there are, so I was thinking something like this might work:

for ($i = 1; is_int($_POST['ap_itemcode_'.$i]); $i++) {
//Add new item and its attributes to array
}

Any help with this would be much appreciated. Thanks.

The numbers in the variable names are consecutive. That number is just the item’s position in the shopping cart. The actual “item number” is stored in the [‘ap_itemcode’] variable. Ditch’s solution should do the job. Thanks for the replies.

Your for loop relies on the assumption that the item numbers are consecutive. If at any point the $_POST contains 1,2 and 4, the 4 will never be reached because is_int($POST['ap_itemcode’.$i]) will be false for $i=3 and thus the loop stops.

The usual way I go about this is:

foreach($_POST as $key=>$val)
{
if (substr($key, 0, 12) == 'ap_itemcode_'))
{
$itemNo=substr($key,12);
// do something with the item, using:
// - $_POST['ap_itemname_'.$itemNo]
// - $_POST['ap_itemcode_'.$itemNo]
// - $_POST['ap_amount_'.$itemNo]
}
}

Of course to make it more secure you’d need to check if $POST['ap_itemname’.$itemNo] and $POST['ap_amount’.$itemNo] are actually set, but I’ll leave that as an exercise to you

That won’t work, firstly because the for loop is all messed up. Secondly, your technique requires variable variables, which is not the best way to go about it.

if you do a simple

print_r($_POST);

you will see that all your values are already in an array. (unsure about the multidimensional part), but test it out.