doulianxi0587 2015-03-23 05:24
浏览 32
已采纳

我得到未定义的偏移错误PHP

I am trying to split the Content that is fetching from DB a few words next to image and a remaining content in the below paragraph

I am getting undefined offset error : 41

the below is the code... it executes correctly but with notice error as above... Can you please help me to fix it.

<div class="contentfont" style="padding-left:20px; text-align:left;">
<?php 

$words = explode(" ",$dcontent);
$cntWords = count($words); 
$splitWords = round($cntWords/2);

for ($i=0;$i<=$splitWords;$i++)
{
print $words[$i].' ';
$halfPoint = $i;
}
?>

<p class="contentfont" style="padding-top:10px;">
<?php 
for ($i=$halfPoint;$i<=$cntWords;$i++) 
{
print $words[$i].' ';// This print statement is causing me this error     Notice: Undefined offset: 41 in D:\xampp\htdocs\training\admin-panel\php\sai_devotees_detail.php on line 106
}
?>
</p>
  • 写回答

1条回答 默认 最新

  • dqrqp8492 2015-03-23 05:30
    关注

    Undefined offset in this case means you are reading past the length of the $words array. Try $cntWords - 1 for ceiling of the loop like this:

    for ($i = $halfway; $i <= $cntWords -1; $i++) {
    

    $halfPoint = $i; is also outside the loop. Try this instead:

    for ($i = 0; $i <= $splitWords; $i++) {
        print $words[$i] . ' ';
        $halfPoint = $i;
    }
    

    When you make a loop in PHP without brackets, only the first statement after it will be executed. So in this case, $i doesn't exist for you to assign it to $halfPoint. Don't think it's clever to compact everything into one line. It will only cause you problems.

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

报告相同问题?

悬赏问题

  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!