使用For循环来调用函数

时间:2015-12-27 19:05:43

标签: php function for-loop

我需要一些帮助来完成我的项目。

3个变量:

$cityName1 = "New York";
$cityName2 = "Madrid";
$cityName3 = "Paris";

功能:

function cityNameFunction($cityName) {
    $city_name = $cityName;
    return $city_name;
}

调用该函数:

$cityName = array();
for($x = 1; $x <= 3; $x++) {
    $cityName[$x] = ${'cityName'.$x};
}
$cityName1 = cityNameFunction($cityName1);
$cityName2 = cityNameFunction($cityName2);
$cityName3 = cityNameFunction($cityName3);

如果我有2000个城市,我该怎么办?

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

奇怪的例子,但你可能会写这样的东西

$cityName = array();
for ($x = 1; $x <= 3; $x++) {
    $cityName[$x] = ${'cityName'.$x};
    ${'cityName'.$x} = cityNameFunction(${'cityName'.$x});
}

答案 1 :(得分:0)

在工作中迭代PHP函数的一个例子:

$new = array(1,2,3,4);
    for($i=0;$i<=3;$i++)
    {
        $val = $new[$i];
        if(!function_exists('myfunction'))
        {
            function myfunction($value) {
                //Do something
            }
        }
        echo $val;
    }