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.

 

Link to comment
Share on other sites

<?php

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

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

?>

Link to comment
Share on other sites

<?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.

Link to comment
Share on other sites

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();

?>

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.   Restore formatting

  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.

×
×
  • 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.