I am new to PHP and I'm trying to convert a simple Javascript function into a PHP function. So far I know to only convert the variables, I need help with the sort function and array filter. Thanks for any help!
var closeRoll = function( number ) {
var rollArray = [36, 48, 60, 72];
var closest = rollArray.filter(function(ele){
return ele - number >= 0
}).sort()[0];
return closest;
};
My half conversion:
function closeRoll( $number ) {
$rollArray = Array(36, 48, 60, 72);
$closest = array_filter( $rollArray, function temp( $rollArray ) {
return $rollArray - $number >= 0;
}); //.sort()[0];
return $closest;
};
Scoping does not work quite like JavaScript; you can't simply refer to $number
inside your callback function, because it does not have a scope chain.
You either have to make it global (not recommended but simple):
<?php
function doFilter($element) { // this could still be anonymous, but doesn't have to be
return $element - $GLOBALS['number'] >= 0;
}
function closeRoll( $number ) {
$GLOBALS['number'] = $number;
$rollArray = Array(36, 48, 60, 72);
$closest = array_filter( $rollArray, 'doFilter' );
return $closest;
};
?>
Or you could utilize the use
operator (an elegant solution):
<?php
function closeRoll( $number ) {
$rollArray = Array(36, 48, 60, 72);
$closest = array_filter( $rollArray, function( $element ) use ($number) {
return $element - $number >= 0;
});
return $closest;
};
?>
You're pretty close, the variable scope in PHP is a little different:
function closeRoll( $number ) {
$rollArray = Array(36, 48, 60, 72);
$closest = array_filter( $rollArray, function($rollArray) use ($number) {
return $rollArray - $number >= 0;
}); //.sort()[0];
return $closest;
}
Basically the different is use ($number)
and you don't need to name the temp function.
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