开发者

PHP pass by reference issue - can't change type?

I have a weird phenomenon. I hope someone can explain to me what is happening there: I want to create a filter. The origin is something like '-10' or '10-20' or '20+' (type string) and the result should be 'Under $10', ... as well as 'product_price < 10', ... for a sql command.

But storing the array back on the original string doesn't work. It just delivers '$Array' as result. Is it not possible to pass by reference开发者_StackOverflow社区 and change the type?

Thanks for your knowledge!

    foreach($filters as &$filter){
        preg_match ('#^\-(\d+)$#ism', $filter, $match);
        if ($match[1]){
            $filter = array(
                'Under $'.intval($match[1]), 
                'product_price < '.intval($match[1])
            );
        }
        ...
    } 
    return $filtering;
}

P.S.: I am not looking for a solution, because I could change the origin string into array, or I could change the foreach in to a pass by value and create a new array with the arrays like $newFilter[] = ... I am only curious


You can change it's type. Proof by construction:

<?php
header('Content-type:text/plain');

        $arr = array(
                '1',
                '2',
        );

        foreach ($arr as &$filter) {
                $filter = array($filter);
        }

        print_r($arr);
?>

Prints:

Array
(
    [0] => Array
        (
            [0] => 1
        )

    [1] => Array
        (
            [0] => 2
        )

)


You should change your foreach into

foreach($filters as $index => $filter)

and update your filter by doing

$filters[$index] = array(...);

I believe the $filter variable created by the foreach() statement is a copy of the data in the array and not a reference to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜