简体   繁体   English

参考正在将项目添加到数组

[英]Reference is adding item to array

I have the following method where you pass a list of items in, and the first item is what you want to see if it exists, and the following items are the path to the item. 我有以下方法,您可以在其中传递项目列表,第一个项目是要查看是否存在的项目,以下项目是项目的路径。

In the following I have 2 print_r statements, one before the for and one after it. 在下面的代码中,我有2个print_r语句,一个在for之前,另一个在它之后。

public function exists(){
    $keys  = func_get_args();
    $value = array_shift($keys);

    $ref = &$_SESSION;
    print_r($_SESSION);
    for($x = 0; $x < sizeof($keys); $x++){
        $ref = &$ref[$keys[$x]];
    }
    print_r($_SESSION);
    if(!is_array($ref)){
        unset($ref);
        return false;
    }
    $found = in_array($value, $ref);
    unset($ref);
    return $found;
}

and when I call it like this: 当我这样称呼它时:

$obj->exists(123, "cart");

I get these two arrays from those print_r 's: 我从那些print_r的两个数组:

Array
(
    [id] => 1
    [email] => xxx@xxx.com
    [user] => TheColorRed
    [first] => Billy
    [last] => Bob
    [ZingLoggedIn] => 1
)
Array
(
    [id] => 1
    [email] => xxx@xxx.com
    [user] => TheColorRed
    [first] => Billy
    [last] => Bob
    [ZingLoggedIn] => 1
    [cart] => 
)

My question is, why is it adding cart to the array? 我的问题是,为什么将cart添加到阵列中? It should only be checking to see if it exists. 它应该只检查它是否存在。

This is the side effect of using references on array elements; 这是在数组元素上使用引用的副作用。 if the element doesn't exist it gets created. 如果元素不存在,则会创建它。 The unset() afterwards doesn't change that. 之后的unset()不会改变它。 Consider not using references; 考虑不使用引用; since you're only reading the values, there should be no copy-on-write taking place: 由于您只读取值,因此不应进行写时复制:

public function exists()
{
    $keys  = func_get_args();
    $value = array_shift($keys);

    $ref = $_SESSION;
    foreach ($keys as $key) {
        if (!isset($ref[$key])) {
            return false;
        }
        $ref = $ref[$key];
    }
    return is_array($ref) && in_array($value, $ref);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM