Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify variables outside of a function in PHP / better way to do something

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?

like image 472
Mankind1023 Avatar asked Dec 04 '22 23:12

Mankind1023


1 Answers

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++;
}
like image 64
Jake N Avatar answered Dec 07 '22 23:12

Jake N