0

The title of the question might hard to interpret, the following is the code that might help

$containers = array(); // array of arrays
for ($index = 0; $index < 4; $index++) {
  $containers[] = array(); // each element of the array is an array
}

foreach ($objects as $object) {
  $index = computeIndex($object); // compute the index into the $containers
  $container = $containers[$index]; // get the subarray object
  $container[] = $object; // append $object to the end of the subarray
  $containers[$index] = $container; // <--- question: is this needed?
}

So as the question shows, do I still need to reassign the subarray back to the array? If its a reference of the element in the array, then I don't think I need.

0

1 Answer 1

2

Yes the last line is needed; array elements are stored as values rather than references. However, PHP will allow you to create a reference with &:

$container = &$containers[$index];
$container[] = $object;

You could also save yourself some trouble and just do:

$containers[$index][] = $object;
Sign up to request clarification or add additional context in comments.

2 Comments

awesome! do I still need the first loop for initializing the $containers?
You do, but you could probably use array_fill instead

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.