duancaiyi7567 2014-04-17 10:36
浏览 104
已采纳

在PHP中增加多个变量For循环

I have a code that separates first from last names, that I am using on a form that could have up to ten names. Right now I have simply replicated the code multiple times, manually updating the number, but figure there has to be a way to loop this function.

The basic code is:

if (!empty($_POST['name2'])) {
    $name2 = ucwords(strtolower($_POST['name2']));
    $parser = new HumanNameParser_Parser($name2);
    $fname2 = $parser->getFirst();
    $lname2 = $parser->getLast();
}

As the fname and lname variables are used elsewhere I need to stick with the naming.

I was thinking to use a For:

for ($i=2; $i <= 6; $i++)
{
    if (!empty($_POST['name($i)'])) {
        $name($i) = ucwords(strtolower($_POST['name($i)']));
        $parser = new HumanNameParser_Parser($name($i));
        $fname($i) = $parser->getFirst();
        $lname($i) = $parser->getLast();
    }
    else
    {
        break;
    }
}

But I am having a tough time figuring what I should actually use for the ($i) in my example. I tried .$i and [$i] but keep getting errors. And not sure if the way I should code it in the $_POST would be different than the variable $name.

  • 写回答

4条回答 默认 最新

  • dsg56465 2014-04-17 10:42
    关注

    for the $_POST variable you can use $_POST['name' . $i] and for the name variable you can just replace it with ${'name' . $i};

    so it will be like this

    for ($i=2; $i <= 6; $i++)
    {
    if (!empty($_POST['name' . $i])) {
        ${'name' . $i} = ucwords(strtolower($_POST['name' . $i]));
        $parser = new HumanNameParser_Parser(${'name' . $i});
        ${'fname' . $i} = $parser->getFirst();
        ${'lname' . $i} = $parser->getLast();
      }  
    else 
      { 
        break;
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加