Jump to content

Send Array As Function Arguments


glenelkins

Recommended Posts

Hi

 

Lets say i have an array like this $args = array ( 'Hi', '24', 'Mark' );

 

and a function:

 

function person ( $msg, $age, $name ) {

}

 

i want to be able to call the function person() parsing the correct parameters from the array, so it would work something like person ( 'Hi', '24', 'Mark' );  not person ( $args );

Link to comment
Share on other sites

You will need to modify your function to allow for a variable number of arguments as well:

function person ( $msg, $age, $name ) {
}

demands 3 arguments, so if the array you're using only has 2 entries, you'll get an error

 

 

Use defaults in the function definition:

function person ( $msg='Hi', $age=32, $name='Mark' ) {
}

 

 

Alternatively

function person () {
   $args = func_get_args();
}

or

function person ($args=array()) {
   foreach($args as $key => $value) {
      $$key = $value;
   }
}

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.