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 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计