Pregunta

I want to write a test case to make sure a function call sets an array; however, I don't find a way to compare two arrays to make sure two empty arrays are not equal.

// 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');
}

So: What is the proper way to compare two PHP arrays and make sure, they are different instances (no matter if the content is the same)?

¿Fue útil?

Solución

Memory locations refers to pointers. Pointers are not available in PHP. References are not pointers.

Anyway, if you want to check if $b is in fact a reference of $a, this is the closest you can get to an actual answer:

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')

I hope this solves your problem.

Otros consejos

try this function . Arrays are compared like this with standard comparison operators

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
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top