Need help creating multi-dimensional array

I want to create a two-dimensional array of information about items in a shopping cart.

The data for the array comes from $_POST variables, which define multiple attributes about multiple items.

Example of some of the $_POST variables:


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.

Should work just fine. I’d use isset() rather than checking with is_int(). Try this:

for ($i = 1; isset($_POST['ap_itemcode_'.$i]); $i++) { 
         $newArray[$i]['name'] = $_POST['ap_itemname_'.$i];
         $newArray[$i]['code'] = $_POST['ap_itemcode_'.$i];
         $newArray[$i]['amount'] = $_POST['ap_amount_'.$i];

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_'))
      // 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 :slight_smile:

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


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