doujing9972 2018-03-31 00:43
浏览 119
已采纳

为什么这个数组元素的值解析为零?

I'm working on pagination for my website, yet I'm stuck on the following piece of code. I've been messing around with it for at least an hour, and can't seem to wrap my head around what's going on with the output.

Of course the if statement executes once.

And as expected the first echo ... returns 1.

However, for some reason the second echo ... returns 0 as a float instead of <div>1</div> as a string...

$rowCount = 5;

$pgCount = ceil($rowCount / 10);

$pgParamArray["page"] = $pgCount;

$pgArray = array("", "", "", "", "");

for ($i = 0; $i < 5; $i++) {

  if ($pgParamArray["page"] - $i > 0) {

    echo $pgParamArray["page"] - $i;

    $pgArray[$i] = "<div>" . $pgParamArray["page"] - $i . "</div>";

    echo $pgArray[$i];

  }

}
  • I have tried setting $pgArray as array() and array($v1, $v2, $v3, $v4, $5) with no luck.

  • Even though var_dump($pgParamArray) returns float, I tried converting $rowCount, which is initially a string from the database, to a number anyways. No dice again.

  • echo $pgArray["0"] also returns 0.

  • var_dump($pgArray[0]) also returns float.

  • var_dump($pgArray) obviously returns array.

  • However, var_dump($pgArray) returns array(5) { [0]=> string(7) ...

I have absolutely zero idea why $pgArray[0] returns 0, yet var_dump($pgArray) returns array(5) { [0]=> string(7) .... That makes zero sense to me. Anybody know why $pgArray[0] is resolving to 0?

  • 写回答

2条回答 默认 最新

  • duanguoping2016 2018-03-31 01:00
    关注

    Wrapping your statement in parenthesis seems to work for me:

    $pgArray[$i] = "<div>" . ($pgParamArray["page"] - $i) . "</div>";
    

    Without the parenthesis, it seems that the value breaks completely; the page doesn't print the <div> tags at all, but rather just adds a trailing 0 to the already printed 1.

    I would assume that it's due to how PHP processes string concatenation, though I wouldn't be able to give you an exact answer as to why this happens. Just to be safe, I'd always either store any equations in variables before you pass them in, or perform all operations inside of parenthesis.

    That way, you won't have weird encounters like this (for example):

    echo "<div>" . 1 + 1 . "</div>";     // returns 1
    echo "<div>" . (1 + 1) . "</div>";   // returns 2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛