Jump to content

[SOLVED] how to check th-run inside a function?


diamondnular

Recommended Posts

Hi folks,

 

I am coding a page, and the page will call one php function several times. Here is how it works:

<?php 
function display() {
  // check if run the first
  // first run task
  echo 'FIRSTRUN - ';
  // if not the first, then neglect
  echo 'test' . "\n";
}
?>

so for example, if the function is called 5 times when the page is loaded, the result will be

FIRSTRUN - test
test
test
test
test

 

Anybody has an idea that will be possible to do? Note that the th-running check is implemented each time the page is loaded, not just the very first time when the function is called.

 

Thanks,

 

D.

 

<?php

function display() {
    static $foo = false;
    if (!$foo) {
        echo "FIRSTRUN - \n";
        $foo = true;
    } else {
        echo 'test' . "\n";
    }   
}
?>

 

Wow, it is so simple that I can not figure it out :) Thanks a bunch Thorpe. Just another question: can we implement this for the th-running? For example, the check will run if the th-run is third, and will not if others.

 

Thanks,

 

D.

Of course you can, a little logical thinking goes a long way.

 

<?php

function display() {
    static $foo = 1;
    if ($foo == 3) {
        echo "Third run\n";
    } else {
        echo "Do nothing\n";
    }
    $foo++;
}

display();
display();
display();
display();

?>

Of course you can, a little logical thinking goes a long way.

 

<?php

function display() {
    static $foo = 1;
    if ($foo == 3) {
        echo "Third run\n";
    } else {
        echo "Do nothing\n";
    }
    $foo++;
}

display();
display();
display();
display();

?>

 

Thank you very much Thorpe :).

 

D.

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.