【问题标题】:Comparing (empty) arrays in PHP在 PHP 中比较(空)数组
【发布时间】:2014-04-01 11:57:06
【问题描述】:

我想编写一个测试用例来确保函数调用设置一个数组;但是,我找不到比较两个数组以确保两个空数组不相等的方法。

// 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 数组并确保它们是不同的实例(无论内容是否相同)的正确方法是什么?

【问题讨论】:

  • 我不确定如何检查两个数组是否相同,但一种选择可能是事后更改 $input 并检查是否相等。

标签: php arrays testing tdd phpunit


【解决方案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')

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

【讨论】:

  • 看看这个link
【解决方案2】:

试试这个功能。像这样使用标准比较运算符比较数组

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
}

【讨论】:

  • 这不适用于 OP 示例,因为数组具有相同的内容但是不同的实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多