dongni1892 2011-06-08 17:35
浏览 35
已采纳

php函数与数组

I want to pass one argument to a function, rather than multiple arguments, that tend to grow unexpectedly. So I figure an array will get the job done. Here's what I've drafted so far...

<?php


function fun_stuff($var){
// I want to parse the array in the function, and use 


}


$my = array();
$my['recordID'] = 5;
$my['name'] = 'John Smith';
$my['email'] = 'john@someemail.com';

echo fun_stuff($my);

?>

I haven't quite grasped the concept of parsing an array. And this is a good way for me to learn. I generally pass the same variables, but on occasion a record does not have an email address, so I do need to make a condition for missing keys.

Am I doing this right so far? Can I pass an array as an argument to a function? And if so, how do I parse and search for existing keys?

  • 写回答

11条回答 默认 最新

  • dongqie7806 2011-06-08 17:43
    关注

    Yes you are on the right track. The approach I take is put required paramters as the first parameters and all optional parameters in the last argument which is an array.

    For example:

    function fun_stuff($required1, $required2, $var = array()) {
       // parse optional arguments
       $recordId = (key_exists('recordID', $var) ? $var['recordId'] : 'default value');
       $name = (key_exists('name', $var) ? $var['name'] : 'default value');
       $email = (key_exists('email', $var) ? $var['email'] : 'default value');
    }
    

    Then you can call your function like so:

    fun_stuff('val 1', 'val 2', array(
        'recordId' => 1,
        'name' => 'John',
        'email' => 'john@stackoverflow.com'
    ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(10条)

报告相同问题?