函数与一个参数的mutliple

时间:2015-06-11 13:58:12

标签: php arrays

我正在创建一个函数来输出某些代码行,具体取决于函数的第一个参数,例如到目前为止这是函数:

function custom_func($info) {
    if ( is_numeric($info) ) {
        $array = array('<tag1>', '<tag2>', '<tag3>');
        echo $array[$info]'
        ';
}

但是,我希望能够输入多个$ info输入,例如当前:

custom_func(0);返回<tag1>

我想:

custom_func(0 1);返回<tag1> <tag2>

这可能吗?

3 个答案:

答案 0 :(得分:0)

您正在寻找func_num_args,它返回传递给函数的参数数量及其姐妹func_get_args,它返回一个包含函数参数列表的数组。

答案 1 :(得分:0)

你可以这样做:

function customFunc() {
    $output = [];

    foreach (func_get_args() as $arg) {
        $output[] = '<tag'.$arg.'>';
    }

    return $output;
}

print_r(customFunc(1, 2, 3));

答案 2 :(得分:0)

我建议你将参数作为数组传递,但是如果你仍然需要传递字符串的解决方案,每个都用空格分隔。尝试下面的功能。

function custom_func($info) {
    if(!empty($info)){
        $arr = explode(' ', $string);
        $tags = array();
        foreach($arr as $value){
            if ( is_numeric($value) ) {
                $tags[] = '<tag'.$value.'>';
            }
        }
        return $tags;
    }
    return null;

}

并尝试出来:

print_r(custom_func('1 2 3 4 10 12 15'));