Page 1 of 1

Selecting part of a multidimensional array

Posted: Sun Sep 19, 2010 7:29 am
by cymric
I have this somewhat embarrassingly simple problem with arrays I can't seem to figure out. I apologise for the title of this thread, it doesn't quite seem to cover what I want, but the code should clear up matters soon enough. Here goes:

Code: Select all

...
/* $id has been set to some integer value */
$result[$id] = array('foo' => $foo, 'bar' =>$bar, 'files' => array());
...
$files = $result[$id]['files'];
$handle = opendir('somedir');
while (($file = readdir($handle)) !== false)
    $files[] = $file;
...
So basically I have this array $result containing another array in $result[$id]['files'], and I want to fill that array with the names of the files of a given directory. In order to save on typing and to speed up processing I cache the array I want to fill in a variable $files, so naturally I would assume that when I start adding to this array, PHP would do The Right Thing and fill in $result[$id]['files']. This trick works in C, and it works in Javascript too. But the funny thing is: it doesn't with PHP. Instead it appears as if it fills up an array which is totally separate from the one in $result[$id]['files'].

My question: why doesn't the above work, and can I make it work without explicitly writing

Code: Select all

    $result[$id]['files'][] = $file;
in the while()-loop?

Re: Selecting part of a multidimensional array

Posted: Sun Sep 19, 2010 8:04 am
by requinix
Normal assignment makes copies. You're adding files to a copy of that array. The only exception is when you're using PHP 5 and assigning objects.

You can force a "by-reference" assignment with a =&.

Code: Select all

$files =& $result[$id]['files'];
But be careful: if you $files= anywhere later you will be destroying the list of files - not changing the $files variable itself.

Re: Selecting part of a multidimensional array

Posted: Sun Sep 19, 2010 8:15 am
by cymric
Ahaaaa... Should've spotted that. Still, thanks for the answer!