Elegance accessory Elegance accessory - 27 days ago 8
PHP Question

save expression in variable php

I'm trying to store expression in variable and then use it in array_filter to return data based on this value for example

$condition = '== 100';

$test = array_filter($last,function ($data)use ($condition){
return $data['rating'] .$condition;
});

var_dump($test);


I tried to use
html_entity_decode($condition, ENT_QUOTES);
preg_replace( )
str_replace()
as well as trim in order to remove the single quotes but it didn't work

I have many condition and I don't want to write
array_filter
many times is there a way to do this ? or better way then the one I'm trying to achieve.

Answer Source

I assumed that you have a limited number of comparison operators you are considering. For reasons of simplicity I numbered them 0,1,2,.... They will trigger different kinds of comparisons inside your filter callback function:

funcion myfiltarr($arr,$operator,$value){
  $test = array_filter($last,function ($data) use ($operator, $value){
     $v=$data['rating'];
     switch($operator) {
       case 0: return $v == $value;
       case 1: return $v < $value;
       case 2: return $v > $value;
       case 9: return preg_match($value,$v);
       // to be extended ...
       default: return true;
     }
  });
  return $test
}

$test=myfiltarr($last,0,100);      // test: "== 100"
var_dump($test);

$test=myfiltarr($last,9,'/^abc/'); // test: "match against /^abc/"
var_dump($test);

Edit: I extended the original answer by a preg_match() option (comparison code: 9). This option interprets the given $value as a regular expression.