Jump to content

if/else withiin a for loop


wigglesby

Recommended Posts

Hi

 

I have a for loop, which does a count and outputs an unordered list only if the criteria in the loop is made:

 

<?php
  		echo '<div id="box_info_downloads">';
        echo '<h2>downloads</h2>';
        echo '<div id="files">';
		echo '<ul class="attached_files">';

	  $limit = 4;
      for ($i=1; $i<= $limit ;$i++) {
          $file = call_user_func(array($facility, 'getFile'.$i));
          $filedesc = call_user_func(array($facility, 'getFileDesc'.$i));

          if(empty($file)){
            echo ' ';
          }
          else{
			  $img = image_tag('pdf.jpg', array('height'=>'30', 'width'=>'30'));
              $filedesc = ( $filedesc !== '' ) ? $filedesc  : 'Download File';
              echo "<br /><li><a href=\"/preview/uploads/facilities/{$file}\">{$img}</a> <br /> {$filedesc}<br /></li>";
           }
      }?>

 

Now at the moment, that will display the <div id="box_info_downloads"> even if no records are found.

I want to have the <div> only displayed if the for loop is successful at with its parameters.

 

How would I do that?

 

Thanks

 

Link to comment
https://forums.phpfreaks.com/topic/184007-ifelse-withiin-a-for-loop/
Share on other sites

<?php
$limit = 4;
$output = "";
for ($i=1; $i<= $limit ;$i++) {
$file = call_user_func(array($facility, 'getFile'.$i));
$filedesc = call_user_func(array($facility, 'getFileDesc'.$i));
if(empty($file)){
	$output .= ' ';
}else{
	$img = image_tag('pdf.jpg', array('height'=>'30', 'width'=>'30'));
	$filedesc = ( $filedesc !== '' ) ? $filedesc  : 'Download File';
	$output .= "<br /><li><a href=\"/preview/uploads/facilities/{$file}\">{$img}</a> <br /> {$filedesc}<br /></li>";
}
}

$style = "";
if (strstr($output, "preview/uploads") === False) {
$style = 'style="display:none;"';
}
$output = '<div id="box_info_downloads" ' . $style . '>
<h2>downloads</h2>
	<div id="files">
		<ul class="attached_files">' . $output;

echo $output;
?>

 

That is one way to do it, generally you do not want to output stuff in the middle of processing scripts, it is generally better to store it in a variable and echo it after the script is processing as it can screw with header and make them not work. Hopefully that is what you were after.

 

EDIT:

Fixed a syntax error (added semicolon after $output = "")

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.