Skip to content

Instantly share code, notes, and snippets.

@nabeelio
Created February 24, 2011 02:06
Show Gist options
  • Save nabeelio/841613 to your computer and use it in GitHub Desktop.
Save nabeelio/841613 to your computer and use it in GitHub Desktop.
array as function parameters
<?php
// Setup our options for what we want to pass
$options = array(
'parameter1'=>'apples',
'parameter3'=>'grapes',
);
some_function($options);
function some_function($options)
{
// Now these are the defaults
$defaults = array(
'parameter1'=>'oranges',
'parameter2'=>'watermelons',
'parameter3'=>'grapefruit',
'parameter4'=>''
);
/* Now we merge the two arrays, except the $options
array takes precedence */
$options = array_merge($defaults, $options);
/* extract() creates a variable with every key from the array
so we can use that variable directly, this is optional */
extract($options);
// So now we can use the variables directly
echo $parameter1; // This will echo &quot;apples&quot;
echo $parameter2; // This will echo &quot;watermelons&quot;
/* Suppose parameter4 has to be set, so we will trigger an error
You can use throw as well if it's in a try/catch block */
if($parameter4 == '')
{
trigger_error('Parameter 4 must be set to this value or that value', E_USER_WARNING);
}
/* Or, if you assume that the $defaults set with '' are mandatory to fill out,
you can use this code */
foreach($defaults as $name=>$value)
{
if($values == '' && $options[$name] == '' || !isset($options[$name]))
{
trigger_error("{$name} is blank, must have a value", E_USER_WARNING);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment