2014-02-28 62 views
1

我想编写一个测试用例以确保函数调用设置了一个数组;然而,我没有找到一种方法来比较两个数组,以确保两个空数组不相等。在PHP中比较(空)数组

// code to be tested (simplified) 
$foo = null; 
function setFoo($input) { 
    global $foo; 

    $foo = array(); // BUG!!! The correct line would be: $foo = $input; 
} 

// test code 
// given 
$input = array(); 
// when 
setFoo($input); 
// then 
if ($foo !== $input) { 
    // this block is not executed because "array() === array()" => true 
    throw new Exception('you have a bug'); 
} 

因此:什么是比较两个PHP数组并确保它们是不同的实例(不管内容是否相同)的正确方法?

+0

我不知道如何检查两个数组是否是相同的实例,但一个选项可能是后来更改'$ input'并检查是否相等。 – Jim

回答

1

内存位置指的是指针。指针在PHP中不可用。引用不是指针。

无论如何,如果你想检查是否$b事实上是$a的参考,这是你可以得到一个实际的答案最接近:

function is_ref_to(&$a, &$b) { 
    if (is_object($a) && is_object($b)) { 
     return ($a === $b); 
    } 

    $temp_a = $a; 
    $temp_b = $b; 

    $key = uniqid('is_ref_to', true); 
    $b = $key; 

    if ($a === $key) $return = true; 
    else $return = false; 

    $a = $temp_a; 
    $b = $temp_b; 
    return $return; 
} 

$a = array('foo'); 
$b = array('foo'); 
$c = &$a; 
$d = $a; 

var_dump(is_ref_to($a, $b)); // false 
var_dump(is_ref_to($b, $c)); // false 
var_dump(is_ref_to($a, $c)); // true 
var_dump(is_ref_to($a, $d)); // false 
var_dump($a); // is still array('foo') 

我希望这能解决你的问题。

+0

Tkae看看这个[链接](http://stackoverflow.com/questions/4110973/compare-php-arrays-using-memory-references)。 – akm

0

试试这个功能。数组像这样与标准比较运算符进行比较

function standard_array_compare($op1, $op2) 
{ 
    if (count($op1) < count($op2)) { 
     return -1; // $op1 < $op2 
    } elseif (count($op1) > count($op2)) { 
     return 1; // $op1 > $op2 
    } 
    foreach ($op1 as $key => $val) { 
     if (!array_key_exists($key, $op2)) { 
      return null; // uncomparable 
     } elseif ($val < $op2[$key]) { 
      return -1; 
     } elseif ($val > $op2[$key]) { 
      return 1; 
     } 
    } 
    return 0; // $op1 == $op2 
} 
+0

你可以在php文档中看到这个。 http://in1.php.net/ternary – joe

+1

这不适用于OP的例子,因为数组有相同的内容,但是不同的实例。 – Jim