2014-07-24 09:04

PHP:foreach in function with array parameter call


I have this code and it works:

            function no_name($paramOne) { 
                $param = array("mihai", "jon", "michael");
                $param[] = $paramOne; 
                foreach($param as $value) { 
                    echo($value . " sunt cel mai bun " . "<br/>"); 
            $string = "dan";


mihai sunt cel mai bun
jon sunt cel mai bun
michael sunt cel mai bun
dan sunt cel mai bun 

But how can I add more names like: "costel", "mihaela", "george" to one array and call function with array parameter to further update names?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dptiq46022 dptiq46022 7年前

    If i understood correctly, you're trying to pass an array to the function instead of a string? If so, instead of appending to the $param array, you could do an array merge.

    function no_name(array $paramOne) { 
        $param = array("mihai", "jon", "michael");
        $param = array_merge($param, $paramOne); 
        foreach($param as $value) { 
            echo($value . " sunt cel mai bun " . "<br/>"); 
    no_name(array("dan", "costel", "mihaela", "george"));
    点赞 评论 复制链接分享
  • dongpao1926 dongpao1926 7年前

    I would just pass the whole array to the function, without hardcoding anything in it.

    But if you want to stick with your method, use func_get_args():

    function please_call_me_everything_but_no_name(){
      static $defaults = ['some', 'names'];
      foreach(array_merge($defaults, func_get_args()) as $value){
        // do your stuff

    And you call it as:

    please_call_me_everything_but_no_name('other', 'words');
    点赞 评论 复制链接分享