I've searched for this for quite a while now and I cannot figure out why my code isn't working how it appears. I'm not sure if I'm having a block or anything but here goes:
$start = 1;
$sstart = strval($start);
$scan = scandir('upload');
$result = null;
while($result==null)
{
foreach($scan as $value)
{
if(strpos($value,$start) == false)
{
$result = $start;
break 2;
}
else
{
$start = $start + 1;
break;
}
}
}
Essentially, I want to scan my directory 'upload'
for any files with the number held in $start
. If this value ISN'T found, then $result
takes the value of $start
and the while()
loop ends. Otherwise I increment $start
and proceed to check every file in the directory again.
Now I have a very similar function like this running on another page that works flawlessly. However this always seems to stop at 1.
There is DEFINITELY a file in my upload folder called showreel1.wmv
and it definitely scans this. (Have echo'd the scandir array) However, it never seems to switch to the else
block but carries on setting $result
as if it never found the value '1'.
I have also tried using $sstart
in the strpos()
function and it has no effect, this of course changes the value of $start
into a string.
Can you guys shed any light on this for me please?
I hope I understood what you're trying to do, try with this:
while($result === null)
{
$found = false;
foreach($scan as $value)
{
if(strpos($value,$start) !== false)
{
$found = true;
$start = $start + 1;
break;
}
}
if(!$found)
{
$result = $start;
break;
}
}
By the way, you should learn how to use ===
operator, it's essential to correctly use strpos()
strpos returns 0 if the haystack begins with the needle you're searching for
This line will return a false positive (ie, it'll tell you it doesn't contain the string even if it actually starts with the string)
if(strpos($value,$start) == false)
You need to use the ===
operator to match exactly false
if(strpos($value,$start) === false)
Instead of scandir, you can also use the RecursiveDirectoryIterator. You can skip the . and .. much more easily, and you will also get the basepath, subpath etc. While it's not your problem, it might ease your development.
You are always breaking out of the foreach statement, so you are only checking the first file in the directory. I guess the firstfile in the directory has a name with a number in it, else it would be an eternal loop.
while($result==null)
{
foreach($scan as $value)
{
if(strpos($value,$start) == false)
{
$result = $start;
break 2; //end the while loop
}
else
{
$start = $start + 1;
break; //end the foreach, but result = null so start with a new foreach
}
}
}
I guess you want to find the lowest number not in any file. In that case I would use
$start = 0; //start with zero because I increase it before the check
$result = null;
while($result==null)
{
$start++;
$found = false;
foreach($scan as $value)
{
if(strpos($value,$start) !== false) {
$found = true;
break; //end the foreach
}
}
if (!$found)
$result = $start;
}