Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increasing Array Size dynamically

Tags:

asp-classic

I have this array in ASP

CONST CARTPID = 0
CONST CARTPRICE = 1
CONST CARTPQUANTITY = 2
dim localCart(3,20)

I add items to this array dynamically like this

localCart(CARTPID,i) = productId
localCart(CARTPRICE,i) = productPrice
localCart(CARTPQUANTITY,i) = 1

The problem is, after 4 items, I can still add the items but UBound always return 3. Which causing my conditions failing.

I want to increase size of this array at run time so that UBOUND can return latest value.

Please let me know how can i do that. Here is my complete code

'Define constants
 CONST CARTPID = 0
 CONST CARTPRICE = 1
 CONST CARTPQUANTITY = 2

 'Get the shopping cart.
 if not isArray(session("cart")) then
dim localCart(3,20)
 else
localCart = session("cart")
 end if

 'Get product information
 productID = trim(request.QueryString("productid"))
 productPrice = trim(request.QueryString("price"))

 'Add item to the cart

 if productID <> "" then
foundIt = false
for i = 0 to ubound(localCart)
    if localCart(CARTPID,i) = productId then
        localCart(CARTPQUANTITY,i) = localCart(CARTPQUANTITY,i)+1
        foundIt = true
        exit for
    end if
next
if not foundIt then
    for i = 0 to 20

        if localCart(CARTPID,i) = "" then
                            ***ReDim Preserve localCart(UBound(localCart, 1) + 1,20)***
            localCart(CARTPID,i) = productId
            localCart(CARTPRICE,i) = productPrice
            localCart(CARTPQUANTITY,i) = 1
            exit for
        end if
    next
end if
 end if
like image 805
VJV Avatar asked Jan 03 '12 06:01

VJV


2 Answers

If your adding the items dynamically in a loop you'll want to use the Redim Preserve() statement. You'll want to use the Preserve part so you don't lose any of your existing data.

Otherwise if your using the array data and then redimming it for another set of data you can just the Redim() statement

Here is a good reference on using Redim() / Redim Prevserve() Statments: http://classicasp.aspfaq.com/general/can-i-create-an-array-s-size-dynamically.html

like image 194
Robert Avatar answered Oct 13 '22 20:10

Robert


The first dimension is only 3 in length, while the second dimension is 20. If you want the UBound of the second dimension, do this:

UBound(localCart, 2)

Which returns 20. You should be able to combine this with ReDim Preserve.

like image 37
Sneal Avatar answered Oct 13 '22 22:10

Sneal