Page 1 of 1

foreach(array as $var except for specific value)

Posted: Tue Jul 20, 2010 3:10 pm
by db579
I'm trying to use a foreach loop to echo each value stored in an array as variable but as the array is created using the scandir function there are also an extra '.' and '..' value entered (not entirely sure where these come from) which I don't want stored as variable. Have tried reading the foreach manual but can't find any syntax for excluding particular values from the loop. How do I do this? Thanks very much!

Re: foreach(array as $var except for specific value)

Posted: Tue Jul 20, 2010 3:23 pm
by AbraCadaver
I would use glob() instead of scandir(), but to answer your question:

Code: Select all

foreach($array as $var) {
   if($var != '.' && $var != '..') {
      echo $var;
   }
}

Re: foreach(array as $var except for specific value)

Posted: Tue Jul 20, 2010 3:25 pm
by AbraCadaver
And the . is the current directory and .. is the parent directory.

Re: foreach(array as $var except for specific value)

Posted: Tue Jul 20, 2010 3:34 pm
by db579
This works perfectly, thanks very much!! Out of interest though why the glob function rather than scandir? (I'm using scandir to return the names of directories so I won't have an extension or anything to use as the pattern parameter)

Re: foreach(array as $var except for specific value)

Posted: Tue Jul 20, 2010 3:43 pm
by AbraCadaver
db579 wrote:This works perfectly, thanks very much!! Out of interest though why the glob function rather than scandir? (I'm using scandir to return the names of directories so I won't have an extension or anything to use as the pattern parameter)
Well glob() is more flexible in that you "can" match a pattern, but if all you want is all files and dirs, then:

Code: Select all

glob('/path/*');

//for only dirs
glob('/path/*', GLOB_ONLYDIR);

Re: foreach(array as $var except for specific value)

Posted: Tue Jul 20, 2010 3:59 pm
by db579
OK I'm trying to implement your suggestion but can't seem to get glob to work. I tried replacing the

Code: Select all

$array = scandir($path);


with

Code: Select all

$array =  glob('$path*', GLOB_ONLYDIR);


But I'm now not getting anything returned. Is my syntax wrong? Thanks

Re: foreach(array as $var except for specific value)

Posted: Tue Jul 20, 2010 4:12 pm
by AbraCadaver
db579 wrote:OK I'm trying to implement your suggestion but can't seem to get glob to work. I tried replacing the

Code: Select all

$array = scandir($path);


with

Code: Select all

$array =  glob('$path*', GLOB_ONLYDIR);


But I'm now not getting anything returned. Is my syntax wrong? Thanks
Pay attention to double and single quotes: http://www.php.net/manual/en/language.types.string.php

Re: foreach(array as $var except for specific value)

Posted: Tue Jul 20, 2010 4:37 pm
by db579
Thanks a lot for the help. Think I've worked it out now!