Posted By

mscribellito on 04/11/12


Tagged

php jquery grep


Versions (?)

PHP version of jQuery's grep


 / Published in: PHP
 

PHP version of jQuery's grep

  1. <?php
  2.  
  3. function grep(Array $elems, Closure $callback, $inv = false) {
  4.  
  5. $ret = array();
  6. $retVal;
  7. $inv = !!$inv;
  8.  
  9. for ($i = 0, $length = count($elems); $i < $length; $i++) {
  10. $retVal = call_user_func($callback, $elems[$i], $i);
  11. if ($inv !== $retVal) {
  12. $ret[] = $elems[$i];
  13. }
  14. }
  15.  
  16. return $ret;
  17.  
  18. }
  19.  
  20. $arr = array(1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1);
  21.  
  22. print_r($arr);
  23. // 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1
  24.  
  25. $arr = grep($arr, function($n, $i) {
  26. return ($n != 5 && $i > 4);
  27. });
  28.  
  29. print_r($arr);
  30. // 1, 9, 4, 7, 3, 8, 6, 9, 1

Report this snippet  

You need to login to post a comment.