I am trying to create a function to initiate date_compare() which is a usort function for a specific array and key.
function init_date_compare($key, $array) {
$key2 = $key;
function date_compare($a, $b) {
global $key2;
$t1 = strtotime($a[$key2]); $t2 = strtotime($b[$key2]);
return $t2 - $t1;
}
usort($array, "date_compare");
}
$arr = array(array("Aug-2-2012"), array("June-2-2012"));
$arr = init_date_compare(0, $arr);
print_r($arr);
This outputs:
Notice: Undefined index: in...
(So basically null, the scoping did not work).
I am not sure how scoping works with functions inside functions, but if I remember right, it is possible. I tried throwing in some globals and initializing $key2 but I am unable to get this to work.
The reason your code isn’t working is because
global $key2;inside thedate_compare()function will not look for it inside the scopeinit_date_compare(); rather it will expect to find it inside the global scope.Besides that, either the array should be passed by reference (i.e.
&$array) via the function parameters, or the array should be returned from it.Closures would make this a whole lot nicer (PHP >= 5.3):
Another way is by using an object to encapsulate the state: