duangu8264 2016-10-19 10:42
浏览 14
已采纳

我们可以将字符串转换为php中的符号

I'm trying to make a calculator in PHP now I have written a function in php to add few numbers but its concatenate instead of adding it can someone please help me guide me to do the task.

function cal($val1 , $opt , $val2){
  return $sum =  $val1 . $opt . $val2;
}

Now, if I'm calling this function like:

echo cal(4,"+",5);

It returns 4+5 but I'm looking 9 for an answer can it be possible that $opt works as an operator instead of a string and i can add or subtract based on operators like

  • 写回答

4条回答 默认 最新

  • duancong7358 2016-10-19 10:46
    关注

    You should do an if statement or a switch case one;

    example

    if ($opt =='+'){
       return $val1+$val2;
    }else if($opt =='-'){ 
       return $val1-$val2;
    } .... etc
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改