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 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示