Question

I have two arrays which are supposed to be equal.

When var dumping and asserting whether those are equal I get the following output

array(2) {
  [0]=>
  array(3) {
    ["100"]=>         //notice that the key is NOT numeric
    int(0)
    ["strKey1"]=>
    int(0)
    ["strKey2"]=>
    int(0)
  }
  [1]=>
  array(3) {
    ["100"]=>         //notice that the key is NOT numeric
    int(0)
    ["strKey1"]=>
    int(0)
    ["strKey2"]=>
    int(0)
  }
}
There was 1 failure:

1) Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
-    '100' => 0
     'strKey1' => 0
     'strKey2' => 0
+    '100' => 0
 )

A simple foreach loop for both of the arrays mapping the keys to be numeric again, works fine, but is not the prettiest hack within a test.

    $actualArray = array();

    foreach ($actualOriginal as $key => $value) {
        $actualArray[$key] = $value;    
    }

    $expectedArray = array();

    foreach ($expectedOriginal as $key => $value) {
        $expectedArray[$key] = $value;    
    }

Any suggestions why these arrays are not considered equal?

Thanks for any help!

Was it helpful?

Solution

I know only one way how to get numeric string keys: by converting object to array

$object = new stdClass();
$object->{'100'} = 0;
$object->strKey1 = 0;
$object->strKey2 = 0;
$array1 = (array) $object;
var_dump($array1);
//array(3) {
//  '100' => -- string
//  int(0)
//  'strKey1' =>
//  int(0)
//  'strKey2' =>
//  int(0)
//}

So, $array1 is not equal to this $array2

$array2 = array('100' => 0, 'strKey1' => 0, 'strKey2' => 0,);
var_dump($array2);
//array(3) {
//  [100] => -- integer
//  int(0)
//  'strKey1' =>
//  int(0)
//  'strKey2' =>
//  int(0)
//}
var_dump($array1 == $array2);
//bool(false)

It's not a bug: https://bugs.php.net/bug.php?id=61655


Also PHPUnit have its own rules of comparison.

$this->assertEquals($array1, $array1); // Fail
$this->assertEquals($array1, $array1); // Pass

https://github.com/sebastianbergmann/phpunit/blob/3.7/PHPUnit/Framework/Comparator/Array.php

Short description of PHPUnit comparison:

$expected = $array1;
$actual = $array1;

$remaining = $actual;
$equal = TRUE;
foreach ($expected as $key => $value){
    unset($remaining[$key]);} // string numeric keys would not be unsetted.

if ($remaining)
    $equal = FALSE;

var_dump($equal);
//bool(false)

So... you doing it right. To get "normal" array you need to recreate array. You could use foreach. But shoter way is in using serialization functions.

$this->assertEquals(unserialize(serialize($array1)), unserialize(serialize($array1)));
//Pass

But it does not look much better. :^ )

Also you could use assertSame.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top