Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Javascript function into a PHP function

Tags:

javascript

php

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;   
};
like image 437
Joe Fisher Avatar asked Apr 20 '12 16:04

Joe Fisher


2 Answers

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;   
};

?>
like image 165
Kato Avatar answered Nov 14 '22 11:11

Kato


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.

like image 25
hakre Avatar answered Nov 14 '22 12:11

hakre