I have a script with the following part:
function checkDays($oldDate){
// calculate time
// Print table row style based on number of days passed
// (eg less than 1 week, 1 week, 2 weeks, 3weeks+)
}
//Some code
checkdays($value)
I would like to put a counter of how many records of each time period there is, the function itself is inside a loop, so its called for each row of the table, and I can't seem to access variables defined outside the function itself so I can change them (eg. put a counter at the top of the script and modify it from the function).
Some people say use global variables but I understand that is a risk and not recommended. Is there an easy way to access the variables from the function? Also, is there a better way to do what I'm doing here overall?
DO NOT BE TEMPTED TO USE globals
You can pass variables by reference, this means the actual variable is passed rather than a copy of it:
$count = 0;
//Some code
checkdays($value, $count);
checkdays($value, $count);
checkdays($value, $count);
// This will output 3
echo $count;
// Use a & to pass by reference
function checkDays($oldDate, &$count){
// Your code goes here as normal
// Increment $count, because it was passed by reference the
// actual variable was passed
// into the function rather than a copy of the variable
$count++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With