Phraates
Phraates

Reputation: 1

save value of variable in function till the next time function calls

I need some function or solution to save the value of variable in function until the next call of function without connecting to MySQL.

function test($price){

    if(isset($lastPrice)){
          if($lastPrice>$price){
                    return true;
              }
          $lastPrice = $price; 
         }else{
               $lastPrice = $price;
               returne false;
     }
}

$prices= array ( '1' => '2000',
                 '2' => '2100',
         '3' => '2100'
);

foreach($prices as $key = > $price){

    if($this->test($price)){
         echo 'got expensive';
    }
}

In this code i need $lastPrice to be save till the next time that test() get call in foreach,...

Upvotes: 0

Views: 188

Answers (2)

djot
djot

Reputation: 2947

function test($price){ () {
  static $lastPrice;
  ...

Upvotes: 2

Misters
Misters

Reputation: 1347

Try this instead:

$lastPrice = 0;//declaring as global
function test($price){

    if($lastPrice != 0){
          if($lastPrice>$price){
                    return true;
              }
          $lastPrice = $price; 
         }else{
               $lastPrice = $price;
               returne false;
     }
}

$prices= array ( '1' => '2000',
                 '2' => '2100',
         '3' => '2100'
);

foreach($prices as $key = > $price){

    if($this->test($price)){
         echo 'got expensive';
    }
}

Upvotes: 0

Related Questions