tags:

views:

16

answers:

1

Hi, I need to add some new values to array by doing something similar.

$array = array();
$array[7] = 'test1';
$array[7] = 'test2';

The problem is that [7] only takes the last value that was added and not test1. Thanks for any help.

+1  A: 

Declare a new (sub)array at the desired offset, and use [] to append new elements to it:

$array = array();
$array[7] = array();
$array[7][] = 'test1';
$array[7][] = 'test2';
print_r($array);
karim79
Thanks for the reply. How can that be achieved from a foreach loop where [7] is added dynamically? For example. I am displaying the results from a database. There will be multiple [7] and [4] and so on.
moset
if you're looping through an array of rows, something like `$array[$i][] = 'blahblah';` is that what you mean? I'm a bit confused...
karim79
Sorry for the confusion. The loop will display two columns in the database that stores numbers and text values. These numbers are not unique so there will be instances where there will be values that needs to be associated with the same number. So the loop will have the following. `9 -> some text``5 -> some text``9 -> some more text``2 -> some text` and so on.. What I need to do is group those with the same number and place in the same key. An array is needed for this since it will be used further down in the script for other operations. Thanks for the help.
moset
nvm. I have it sorted out. Thanks for the help.
moset