1

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

1
  • I'm not sure how to check to two arrays are they same instance but one option could be to alter $input afterwards and check for equality. Commented Feb 28, 2014 at 13:08

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Tkae a look at this link.
0

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
}

1 Comment

This wont work for OPs example since the arrays have identical contents but are different instances.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.