0

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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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.
if you're looping through an array of rows, something like $array[$i][] = 'blahblah'; is that what you mean? I'm a bit confused...
nvm. I have it sorted out. Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.