Static variable retains their value across multiple function calls. Let us take an example:

$fruits = ['apples', 'oranges', 'grapes'];
foreach( $fruits as $fruit ) {

     $eaten = eat();  // assuming it returns true.
     
     static $eaten_count =  1;
     
     if ( $eaten_count == 1 && $eaten ) {
          echo 'Eaten';
          
          $eaten_count++;
     }
}

Here, the $eaten_count static variable is initialized to 1 and then incremented when if block is entered. So, that the Eaten is echoed only once.

This means $eaten_counts value is retained when the foreach loop continues.

If you don’t add static keyword in that variable, the output will be EatenEatenEaten

Note that duplicate declaration of static variable is considered a fatal error in PHP 8.3.

What is a static variable in PHP?
Tagged on:

Sanjeev Aryal

Don't bury your thoughts, put your vision into reality ~ Bob Marley.

Leave a Reply

Your email address will not be published. Required fields are marked *