March 8, 2012

How to skip a statement execution from the second time if I call the same page again in PHP

Question by AshokiPhone

In my temp_file.php i have a variable (array)

<?php
 $temp = array();
?>

No in my currentPage.php i am using this

<?PHP
   include 'temp_file.php';
   ///giving some value to $id and calling same page again
   array_push($GLOBALS['temp'],$id);   
?>

I want to use this temp array to append a value each time i call the same file(CurrentPage.php) but include ‘temp_file.php’; statement is executing every time and i am getting single element to my array that i was last pushed.

Can any one help me is there any way in php to skip this include statement from second time to till the session end.

Answer by Starx

None of the answers are correct.

include_once() will not work for you, as you will be loading the page again, even if it is the second time, as with every load the php will execute from the top.

Because include_once() will only stop the redundant inclusion in same execution, not multiple.

Here is a simple workaround to your problem

<?PHP
   if(!isset($_SESSION['include']) || !$_SESSION['included'])) {
   // ^ Check if it was included before, if not then include it
       include 'temp_file.php';
       $_SESSION['included'] = true; //set a session so that this part never runs again for the active user session
   }
   ///giving some value to $id and calling same page again
   array_push($GLOBALS['temp'],$id);   
?>

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!