dongyan3018 2017-04-08 05:33
浏览 32
已采纳

for loop使用php反转一个字符串

I am receiving an error Uninitialized string offset:

this is my code

$post = "Test"; 
$strtext = strlen($post);

for($i=strlen($post);$i>=0;$i--)
{
    echo $post[$i];
}

I reviewed my code and I think that all are correct, but I don't think its perfect because it has an error.

result must be tseT without an error. and I am not allowed to use error_reporting(0);

This is our assignment tbh, reverse the string using 1 for loop only.

Thank you for your answers.

  • 写回答

2条回答 默认 最新

  • doushi2902 2017-04-08 05:35
    关注

    Instead of looping it manually use PHP function strrev

    Solution 1:

    <?php
    
    $post = "Test";
    echo strrev($post);
    

    Output:

    tseT
    

    Solution 2:

    $post = "Test";
    
    for($x=strlen($post)-1; $x>=0; $x--)
    {
        echo $post[$x];
    }
    

    Output:

    tseT
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • douqi0090 2017-04-08 05:38
    关注

    Try this:

    for($i=strlen($post) - 1; $i>=0; $i--){
        echo $post[$i];
    }
    

    as the array index are from 0 to n-1

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 我用C语言easyx图形库绘制了一个3d游戏方框透视,但进入游戏时候鼠标准星对准方框边缘 鼠标光标就会弹出来这是啥情况怎样让光标对准绘制的方框点击鼠标不弹出光标好烦这样
  • ¥20 用Power Query整合的问题
  • ¥20 基于python进行多背包问题的多值编码
  • ¥15 相同型号电脑与配置,发现主板有一台貌似缺少了好多元器件似的,会影响稳定性和使用寿命吗?
  • ¥15 要求编写稀疏矩阵A的转置矩阵的算法
  • ¥15 编写满足以下要求的停车场管理程序,设停车场只有一个可停放n辆车的狭窄通道且只有一个大门可供车辆进出。
  • ¥15 C语言:数据子序列基础版
  • ¥20 powerbulider 导入excel文件,显示不完整
  • ¥15 用keil调试程序保证结果进行led相关闪烁
  • ¥15 paddle训练自己的数据loss降不下去