BenM BenM - 1 year ago 46
PHP Question

How do I return literal values of a php string so it runs as code?

I am not sure I am using the right terms even here but I will try and explain, I am using PHP array_filter function to filter products and it callback to a custom function I made where I add the filter(s). I can do this hard-coded very easy, but I obviously want it to be dynamic:

To cut a long story short the custom filter function returns to the array_filter() function like so:

return ($arr['colour']=='Red' || $arr['colour']=='White');

This works fine if hard-coded like the above, and filters the array as expected to only show products that are red or white, however I need this to be dynamic.

So how can I construct a string of values and then use this in the return statement?

For example:

$var="$arr['colour']=='Red' || $arr['colour']=='White'";
return ($var);

Does not work. I have tried using eval() (I don't want to use this any way!) and it didn't work still.

I have a loop as follows constructing the string from an array:

// $value=array of filters e.g colour=Black, colour=Red


//creates array e.g $arr['colour']='Red'

$imploded_filter= implode(" || ", $uniquefilters);
//creates string e.g $arr['colour']='Red' || $arr['colour']='White'

So if I echo $imploded_filter I get the extract string I would like to return

echo $imploded_filter;
// outputs $arr['colour']='Red' || $arr['colour']='White'

However if I do


it obviously isn't evaluating the string as hard code, so what can I do, do I need to do something to the string or return it a different way, or construct the code I need to return in a totally different way?

Thanks for any help!

Answer Source

Array keys can be specified dynamically. There is no need for eval():

$value = $array[$key];

You can build a list of filters and match each of them in the array_filter() callback:

$filters = array(
    array('colour', array('white', 'blue')), // multiple accepted values (OR)
    array('material', 'Fine Bone China'), // single accepted value

$filtered = array_filter($products, function ($item) use ($filters) {
    // match all filters
    foreach ($filters as $filter) {
        // detect multi-value filter
        $isArrayFilter = is_array($filter[1]);

        if (
            // check if multi-value filter doesn't match
            $isArrayFilter && !in_array($item[$filter[0]], $filter[1])
            // check if a single-value filter doesn't match
            || !$isArrayFilter && $item[$filter[0]] != $filter[1]
        ) {
            // filter doesn't match - exclude the item
            return false;

    // all filters match - include the item
    return true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download