Ty44ler Posted June 2, 2011 Share Posted June 2, 2011 I'm trying to get a listing of my directory that shows the first letter and then all the names that start with that letter. Here is my code: for($i = 65; $i < 91; $i++) { foreach (glob("{".chr($i).",".chr($i+32)."}*", GLOB_BRACE|GLOB_ONLYDIR) as $directoryname) { echo chr($i)."| ".$directoryname; } } But here's my output: P | Project Red P | Projects P | Pants R | Resumes W | Warehouse Files W | warrior I want it to be like: P | Project Red Projects Pants R | Resumes W | Warehouse Files Warrior I know I have to move the chr($i) since it loops, but I'm not sure where to go from there. Quote Link to comment https://forums.phpfreaks.com/topic/238165-directory-listing-with-first-letter-displayed/ Share on other sites More sharing options...
mikesta707 Posted June 2, 2011 Share Posted June 2, 2011 you will need to keep track of the last character you output, and if the current character to be output is the same, then you dont output it. Something like //var will keep track of the last value of chr($i) $lastVal = "";//set it to an empty string at the beginning for($i = 65; $i < 91; $i++) { foreach (glob("{".chr($i).",".chr($i+32)."}*", GLOB_BRACE|GLOB_ONLYDIR) as $directoryname) { //here we have a condition that decides if we output the chr($i) | part echo ($lastVal != chr($i)) ? chr($i)."| " : " "; //3 spaces so it looks even echo $directoryname; //now we update our lastVal variable to the current on generated $lastVal = chr($i); } } hope this helps Quote Link to comment https://forums.phpfreaks.com/topic/238165-directory-listing-with-first-letter-displayed/#findComment-1223894 Share on other sites More sharing options...
Pikachu2000 Posted June 2, 2011 Share Posted June 2, 2011 EDIT: Looks like mikesta beat me to it, but this is nearly the same thing anyhow. This seems to work as you describe. Just check what the last output was, and only output the letter if it changes, or is empty (indicating that it was the first iteration). for($i = 65; $i < 91; $i++) { foreach (glob("{".chr($i).",".chr($i+32)."}*", GLOB_BRACE|GLOB_ONLYDIR) as $directoryname) { echo (empty($prev) || chr($i) != $prev) ? chr($i)." | $directoryname<br>" : " $directoryname<br>"; $prev = chr($i); } } Quote Link to comment https://forums.phpfreaks.com/topic/238165-directory-listing-with-first-letter-displayed/#findComment-1223898 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.