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.

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

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)