2

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.

3
  • because i don't yet fully understand it :( Commented May 25, 2011 at 2:45
  • when you get all your code working the way you want it, be sure to edit your post to include it. As it is now, there's some weird curly braces inside the return array( and probably a missing { after if ($activated). I started to do the edits myself, but the intent is unclear where that missing { is. Commented May 25, 2011 at 2:59
  • thanks! In the original code there is no { after if ($activated) perhaps I should add it. hmm i dont see the weird curly braces in the return array. are u sure? Commented May 25, 2011 at 3:03

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ooh I see! thx. can i instead return $data? instead of each value?
1

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

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.