views:

27

answers:

2

Why does this work:

function myfunction($v) {
    $query = $v['host'] == '1';
    return ( $query );
}

$output = array_filter($recordset,myfunction);
print_r($output);

Whereas this script, which tries to accomplish the same thing with variables, does not?

$column1 = 'host';
$value1 = 1;
$query1 = '$v[\''.$column1.'\'] == '.$value1;

function myfunction($v) {
    $query = $GLOBALS['query1'];
    return ( $query );
}

$output = array_filter($recordset,myfunction);
print_r($output);

Any help would be great. Thanks!

A: 

Can you use global $query1?

Lerxst
It doesn't seem to work. When I replaced $query = $GLOBALS['query1']; with $query = $query1; the script stopped working entirely.
Ryan
Then write `global $query1` at the start of the function.
Delan Azabani
+1  A: 

The statement $query = $v['host'] == '1'; doesn't set $query to be the expression $v['host'] == '1'. It evaluates $v['host'] == '1' and sets $query to the value of the expression, which is 1 or 0, depending on whether $v['host'] is equal to '1'.

$output = array_filter($recordset,myfunction); works because array_filter is meant to take a user-defined PHP callback function for its second argument.

Dynamic coding is really only achievable in PHP using the eval function (highly dangerous!) or using an object-oriented structure with object overloading.

amphetamachine
Thanks, this is a great explanation
Ryan