dongshi2141 2015-04-15 13:47
浏览 50
已采纳

如何在PHP中解决var_dump($ testArray)

What is the problem with the code below? What will it output? How can it be fixed?

$referenceTable = array();
$referenceTable['val1'] = array(1, 2);
 $referenceTable['val2'] = 3;
$referenceTable['val3'] = array(4, 5);

 $testArray = array();

 $testArray = array_merge($testArray, $referenceTable['val1']);
 var_dump($testArray);
 $testArray = array_merge($testArray, $referenceTable['val2']);
var_dump($testArray);
  $testArray = array_merge($testArray, $referenceTable['val3']);
   var_dump($testArray);

Thanks

  • 写回答

1条回答 默认 最新

  • dongtan2017 2015-04-15 13:58
    关注

    The output will be as follows:

    array(2) { [0]=> int(1) [1]=> int(2) } NULL NULL

    You may also see two warnings generated, similar to the following:

    Warning: array_merge(): Argument #2 is not an array

    Warning: array_merge(): Argument #1 is not an array.

    The issue here is that, if either the first or second argument to array_merge() is not an array, the return value will be NULL. For example, although one might reasonably expect that a call such as array_merge($someValidArray, NULL)would simply return $someValidArray, it instead returns NULL! (And to make matters worse, this is not documented well at all in the PHP documentation.)

    As a result, the call to $testArray = array_merge($testArray, $referenceTable['val2']) evaluates to $testArray = array_merge($testArray, 3)and, since 3 is not of type array, this call to array_merge() returns NULL, which in turn ends up setting $testArray equal to NULL. Then, when we get to the next call to array_merge(), $testArray is now NULL so array_merge() again returns NULL. (This also explains why the first warning complains about argument #2 and the second warning complains about argument #1.)

    The fix for this is straightforward. If we simply typecast the second argument to an array, we will get the desired results.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?