开发者

How to make a PHP code run only once [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How can I execute a block of code exactly once in PHP?

I have a code that basically checks the current category assigned to the post, and retrieve a code according to it. If there are more then 1 categories assigned to the post, it's rendering both the codes or the same one twice..

I wondered if there's an option to make the code to work only once.

<?php 
foreach((get_the_category()) as $category){ 
  if($category->cat_ID == '4'){ 
    echo "....TEXT...."; 
  } else { 
    echo "....TEXT2....";
  }
}
?&g开发者_Python百科t;

Thanks!


$first = true;    
foreach((get_the_category()) as $category) { 
        if($category->cat_ID == '4') { 
           echo "....TEXT....";
           $first = false;
        } else { 
           echo "....TEXT2....";}
           $first = false;
        }

        if(!$first) break;
    }


Try this:

<?php 
foreach((get_the_category()) as $category){ 
  if($category->cat_ID == '4'){ 
    echo "....TEXT...."; 
  } else { 
    echo "....TEXT2....";
  }
  break;
}

?>

Break is used to get out of loop regardless of the condition. Please refer to this article for manual.


Add a variable to the inside of the loop that flags the code as run. Then check for that variable before running:

<?php 
   if($first_run) {
      foreach((get_the_category()) as $category){ 
         if($category->cat_ID == '4'){ 
               echo "....TEXT...."; 
         } 
         else { 
               echo "....TEXT2....";
         }
        }
      $first_run = TRUE;
      }
        ?>

This will only work if you have the code called from a function or if you are including it multiple times in the same script. If you want it to only run once per session (across several pages), you should use a SESSION variable.


complementing my comment above.

<?php 
      foreach((get_the_category()) as $category){ 
         if($category->cat_ID == '4'){ 
               $varCateg = "....TEXT...."; 
         } 
         else { 
               $varCateg = "....TEXT...."; 
         }
        }

// diplay varCateg here
echo $varCateg; 

?>

doing this will not show up the categ twice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜