Re: re-keying an array

From: Date: Fri, 30 Apr 2004 03:47:35 +0000
Subject: Re: re-keying an array
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-184998@lists.php.net to get a copy of this message
* Thus wrote Justin French (justin@indent.com.au): > On 30/04/2004, at 12:06 PM, John W. Holmes wrote: > > >Although this begs the question of why you'd need to "rekey" an > >array... > > It seemed the easiest way to get the first two elements off the > beginning of the array after shuffle()ing it, or so I thought -- but > I'm more than happy to hear of a better way, as always :) > > My only requirement is really to end up with an array named $files that > can be used later on in the template in a foreach loop. > > <? > shuffle($filenames); // random sort > $filenames = array_values($filenames); // re-key > for($i=0;$i<2;$i++) { > $files[] = "path/to/".$filenames[$i]; > } > ?> Yeah, the array_values is unnecessary: // this will resort the way the items are ordered shuffle($filenames); // random sort Normally a simple foreach loop would work but since you're grabbing the first two, a slice of the array will work: foreach(array_slice($filenames, 0, 2) as $filename) { $files[] = "path/to/" . $filelname; } Curt -- "I used to think I was indecisive, but now I'm not so sure."

« previous php.general (#184998) next »