PHP是通过引用访问的数组元素


php are array elements accessed by reference?

问题的标题可能很难解释,下面的代码可能会有所帮助

$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?
}

因此,正如问题所示,我仍然需要将子数组重新分配回数组吗?如果它是数组中元素的引用,那么我认为我不需要。

是,最后一行是必需的;数组元素存储为值而不是引用。但是,PHP允许您使用&:

创建引用。
$container = &$containers[$index];
$container[] = $object;

你也可以省去一些麻烦,直接这样做:

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