Elegance accessory Elegance accessory - 6 months ago 24
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;


I tried to use
html_entity_decode($condition, ENT_QUOTES);
preg_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
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){
     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"

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download