tags:

views:

58

answers:

3

Hi all,

I have a question about associative arrays in php.

I have following array in which there are two items named 4 and 2 respectively.

$items = array(4,2);

Now i want to associate each item's quantity to it which can be done as follows:

$items['4']=23;
$items['2']=0;

which means that there are 23, 'item 4s' and no 'item 2'.

But I sometimes don't know in advance what is there in the $items so i want to associate quantity on basis of location. I wanted to do something like associate 23 to whatever is there on the zero location of the item array:

$items['items[0]']=23;

This of course did not work because its not the right way to extract whatever is placed on the zero location of items. Can anyone please tell me how do i do that?

+2  A: 

You are confusing in the use of item and items. I imagine you have both an item array and an items array, else things can easily get hairy.

Anyhow, you just refer to it as a variable, not as a string:

$items[$item[0]] = 23;
Vinko Vrsalovic
Aaahaa..Thanks. It worked.sorry about creating the confusion. Its wasn't 'item' but 'items'.thanks again
baltusaj
A: 

Let me get this straight. So you start with an array that looks like this:

$items = array( 0 => 4, 1 => 2 )

And you want to end up with an array that looks like this: ?!

$items = array( 0 => 4, 1 => 2, 2 => 0, 4 => 23 )
newacct
:) hmm....i don't want that. What i wanted has already been answered by Tarnshaf and Vinko. Thanks for your help though.
baltusaj
A: 

I think you should use your array as a kind of "map". The item number is your key, and the quantity your value.

By calling

$items = array(4,2);

you create

$items[0] = 4;
$items[1] = 2;

but you want to use the 4 and 2 as a key in your array. So you should instead use

$items = array( 4 => false, 2 => false );

where false stands for an item that has not yet a quantity associated (could also be e.g. -1). This creates

$items[2] = false;
$items[4] = false;

When using false, you can check for not assigned values by calling

if ($items[4] === false) {
  echo "No quantity set!";
}

And now the second step.. if you want to assign the item #4 a quantity of 23, just call

$items[4] = 23;

So I don't think you will want to rely on the order inside your array..

Tarnschaf