Jump to content
Sign in to follow this  
paulonline2501

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

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

Share this post


Link to post
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

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...