CyberJunkie
CyberJunkie

Reputation: 22674

Passing array to function parameter

Is it ok to pass an array in a function argument? For example,

function something() 
{
if ($this->db->insert($this->table_name, $data)) {
$data = array(
    'user_id' => $this->db->insert_id();
    'first_name' => $this->form_validation->set_value('first_name'),
    'last_name' => $this->form_validation->set_value('last_name'),
    );


 if ($activated)
            $this->create_profile($data);
            return array( //not sure why i'm returning this
                        'user_id' => $user_id,
                        'first_name' => $first_name,
                        'last_name' => $last_name,
    }                   );
    return NULL;
    }

and then pass that to

    private function create_profile($data)
    {
    return $this->db->insert( $this->profile_table_name, $data )
    }

the script is from a codeigniter plugin which I modified, so I'm trying not to butcher it too much.

Upvotes: 2

Views: 567

Answers (4)

Nemoden
Nemoden

Reputation: 9056

It is okay to pass an array as a parameter as well as it is okay to return an array as a result. In PHP we do it all the times.

It is also okay to pass and return arrays in other languages... like in Python they do it often, e.g. process_parameters(*parameters).

It is even okay if you pass an object! Or return an object... Like so:

$dbConnection = get_db_connection('mysql'); // $dbConnection is an instance of MySQLDbConnection now

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270599

It's absolutely fine to pass an array to a function. Many of PHP's own built-in array_*() functions receive array parameters and then return arrays.

And as for returning an array from the function -- that's an excellent way to return multiple values from a single function.

Upvotes: 2

alex
alex

Reputation: 490143

If you need to return multiple values, an array is one way of doing that.

You could also return an object, just instantiate stdClass and set the properties.

Upvotes: 1

ariefbayu
ariefbayu

Reputation: 21979

Is it ok to pass an array in a function argument? => YES!

Upvotes: 1

Related Questions