Reputation: 11
I need a simple counter in php and I know, where the problem is, everytime when I start the function, $counter
will jump again to 0. I don't know how to solve that.
if(empty($_POST["message-to-send"])){
doSomething();
}
function doSomething(){
$counter=0;
$messages = array(
"message1",
"message2",
"message3",
"message4",
"message5"
);
echo $messages[$counter];
$counter++;
if($counter>count($messages)){
echo "something";
}
}
Upvotes: 1
Views: 726
Reputation: 94642
If you make the $counter
a static variable it will maintain its value over many calls
function doSomething(){
static $counter=0;
$messages = array(
"message1",
"message2",
"message3",
"message4",
"message5"
);
echo $messages[$counter];
$counter++;
if($counter>count($messages)){
echo "something";
}
}
doSomething();
doSomething();
RESULT:
message1
message2
Upvotes: 3