douzhun5971 2014-01-11 11:17
浏览 104
已采纳

从String中的某个位置获取一个数字,然后将其用于计算

I'm trying to code a function that will do some mathematical operations. Here's an example:

function test($number){
    $result = 5 * $number[2];
    echo $result;
}

So if I enter a number "12345", I want to multiply the number at index 2 with 5. So in this case, I should be multiplying 5*3 and get 15.

But I always get 0. I found the error why I'm always getting 0. It's because $number[2] isn't working. So how do I get a number at a certain index and then calculate with it?

  • 写回答

1条回答 默认 最新

  • dousou1967 2014-01-11 11:26
    关注

    The problem is that you can get the number by index only of string not of int.

    test("124"); // working
    test(124); // not working
    

    Possible solution is this:

    function test($number){
        $number = "$number";
        $result = 5 * $number[2];
        echo $result;
    }
    
    test(124);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制