Re: SQL Distinct-like behaviour

From: Date: Fri, 24 Aug 2007 03:46:43 +0000
Subject: Re: SQL Distinct-like behaviour
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-261204@lists.php.net to get a copy of this message
Marcelo de Moraes Serpa wrote:
How could I iterate over the files in a directory and build a list of unique filenames? Take the following filelist: file1_01.jpg file2_01.jpg file2_02.jpg file2_03.jpg file3_01.jpg file3_02.jpg file3_03.jpg file4_01.jpg file4_02.jpg file4_03.jpg I would like to build an array like this: $names = ("file1","file2","file3","file4")
As mentioned, use array_unique(). But that'll only help once you've built up an array of filenames (after trimming off the last bit). I think Jay & Hamza missed the fact that the files are *already unique*. One would be hard-pressed to store multiple files with the same name in a directory. So, i'm assuming your filenames wil be more like: foo_01.jpg foo_02.jpg bar_01.jpg etc. IOW, you want to perform a regexp such that you isolate the last part to remove it before shuffling out the dupes. So: $filenames = Array('foo_01.jpg', 'foo_02.jpg', 'bar_01.jpg', 'baz_01.jpg', 'bar_02.jpg'); $out = array_unique(preg_replace('/^([a-z]+)_[0-9]+\.jpg$/', '$1', $filenames)); var_dump($out); --snip-- array(3) { [0]=> string(3) "foo" [2]=> string(3) "bar" [3]=> string(3) "baz" } --snip-- Note that if you might have uppercase letters, dashes, underscores, etc. in the filename you'll need to modify that a bit. Something like: '/^([a-zA-Z-_]+)_[0-9]+\.jpg$/' If you'll have more than one file extension, replace 'jpg' with '[a-z]+' However, the array_unique call will cause, eg. both 'bar_01.jpg' and 'bar_01.png' to output 'bar' only once, which may not be what you want. HTH, brian

« previous php.general (#261204) next »