Can we pass an array as parameter in any function in PHP?

后端 未结 12 577
感动是毒
感动是毒 2021-02-02 06:56

I have a function to send mail to users and I want to pass one of its parameter as an array of ids.

Is this possible to do? If yes, how can it be done?

Suppose w

相关标签:
12条回答
  • 2021-02-02 07:51

    Yes, you can safely pass an array as a parameter.

    0 讨论(0)
  • 2021-02-02 07:51

    Yes, we can pass arrays to a function.

    $arr = array(“a” => “first”, “b” => “second”, “c” => “third”);
    
    function user_defined($item, $key)
    {
        echo $key.”-”.$item.”<br/>”;
    } 
    
    array_walk($arr, ‘user_defined’);
    

    We can find more array functions here

    http://skillrow.com/array-functions-in-php-part1/

    0 讨论(0)
  • 2021-02-02 07:55

    I composed this code as an example. Hope the idea works!

    <?php
    $friends = array('Robert', 'Louis', 'Ferdinand');
      function greetings($friends){
        echo "Greetings, $friends <br>";
      }
      foreach ($friends as $friend) {
      greetings($friend);
      }
    ?>
    
    0 讨论(0)
  • even more cool, you can pass a variable count of parameters to a function like this:

    function sendmail(...$users){
       foreach($users as $user){
    
       }
    }
    
    sendmail('user1','user2','user3');
    
    0 讨论(0)
  • 2021-02-02 07:58

    You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop() (and similar) all you like on it and won't affect anything outside.

    function sendemail($id, $userid){
        // ...
    }
    
    sendemail(array('a', 'b', 'c'), 10);
    

    You can in fact only accept an array there by placing its type in the function's argument signature...

    function sendemail(array $id, $userid){
        // ...
    }
    

    You can also call the function with its arguments as an array...

    call_user_func_array('sendemail', array('argument1', 'argument2'));
    
    0 讨论(0)
  • 2021-02-02 07:59

    Yes, you can do that.

    function sendemail($id_list,$userid){
        foreach($id_list as $id) {
            printf("$id\n"); // Will run twice, once outputting id1, then id2
        }
    }
    
    $idl = Array("id1", "id2");
    $uid = "userID";
    sendemail($idl, $uid);
    
    0 讨论(0)
提交回复
热议问题