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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭