Jump to content

php foreach glob - how to give message if there are no files


paulonline2501

Recommended Posts

Hi,

 

Does any one know how to display a message instead of the warning error when there are no files in the folder you are doing a directory list of?

 

I have the following code, which produces a list of files in the folder.

The only problem is when the folder is empty.

I get a foreach error only when there are no files in the folder.

I can forsee that sometimes the folders will be empty so will want to show my own error instead of this server warning.

 

I think the "GLOB_NOCHECK" function may help but this may actually only work with folders rather than files.

 

 

The code that works when there are files in the folder but gives a PHP warning when there are no files in the folder:

foreach (glob('../../_documents/*.*') as $file){   $fileName = basename($file);   if ($fileName != 'index.php')      {?>	<li><?php echo"$fileName"?></li>      <?php       }	//end if}//end foreach

The warning error i get if there are no files in the folder:

  • Warning: Invalid argument supplied for foreach() in.....

 

I would like to put the following if there is nothing in the folder:

<li>There are currently no files in this folder.</li>
Edited by as_bold_as_love
Link to comment
Share on other sites

I got it working with the following code but if you have any improvements let me know.

 

This code will always display the folder as empty. Opps....

foreach (glob('../../_documents/*.*',GLOB_NOCHECK) as $file){	$fileName = basename($file);	if ($fileName = '*.*'){echo("<li>There are currently no files in this folder.</li>");break;}	if ($fileName != 'index.php') 	{?>		<li><?php echo"$fileName"?></li>		<?php 	}//end if}//end foreach
Edited by as_bold_as_love
Link to comment
Share on other sites

@up, your script wont work, i see some errors.

 

Here it is :-)

<?php	$glob = glob('../../_documents/*.*');	if(isset($glob) && is_array($glob))	{		foreach ( $glob as $file)		{			$fileName = basename($file);			if ($fileName != 'index.php')			{				echo '<li>'.$fileName.'</li>';	      			}		}	}	elseif(empty($glob))	{		echo '<li>There are currently no files in this folder.</li>';	}	else	{		echo '<li>Something went wrong.</li>';	}?>
Edited by aloniie
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...