PHP uses function static variables to implement the method of specifying the number of iterations

  • 2021-09-12 00:45:05
  • OfStack

This article illustrates how PHP uses function static variables to specify the number of iterations. Share it for your reference, as follows:

In PHP, in addition to static member attributes of classes, static variables can also be defined in functions using static. So as to complete the function iteration conveniently.

Example 1:


<?php
function Test()
{
  $a = 0;
  echo $a;
  $a++;
}
?>

In the above example, a is re-assigned to 0 every time the Test function is called, because the variable a is re-assigned to 0 once 1 exits this function, because the variable a does not exist once 1 exits this function. To complete the iteration, you need to write a count function that will not lose the current count value, and define the variable $a as static:


<?php
function test()
{
  static $a = 0;
  echo $a;
  $a++;
}
?>

In this way, $a is assigned only on the first call, and then incremented by 1 on each call, and will not be overridden.

In this way, you can use this feature to specify the number of iterations of an operation:

Example 2: (Get the result of popping an array by 5 elements)


$arr = range(1,10,1);
function test($arr)
{
  static $count=0;
  array_pop($arr);
  $count++;
  if ($count < 5) {
    test($arr);
  }else{
    var_dump($arr);exit;
  }
}
test($arr);

Run results:


array(5) {
 [0]=>
 int(1)
 [1]=>
 int(2)
 [2]=>
 int(3)
 [3]=>
 int(4)
 [4]=>
 int(5)
}

For more readers interested in PHP related contents, please check the topics on this site: "Summary of php String (string) Usage", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php Sorting Algorithm Summary", "PHP Common Traversal Algorithms and Skills Summary", "PHP Mathematical Operation Skills Summary", "PHP Array (Array) Operation Skills Encyclopedia" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: