I'm sure there is a better to this. Any help will be greatly appreciated.
I want to pass an array to a php function that contains the argument and all the arguments are optional. I'm using code ignitor and am by no means an expert. Below is what i have been using so far:
function addLinkPost($postDetailArray) {
if (isset($postDetailArray['title'])) {
$title = $postDetailArray['title']; }
else {
$title = "Error: No Title";
}
if (isset($postDetailArray['url'])) {
$url = $postDetailArray['url'];
} else {
$url = "no url";
}
if (isset($postDetailArray['caption'])) {
$caption = $postDetailArray['caption'];
} else {
$caption = "";
}
if (isset($postDetailArray['publish'])) {
$publish = $postDetailArray['publish'];
} else {
$publish = TRUE;
}
if (isset($postDetailArray['postdate'])) {
$postdate = $postDetailArray['postdate'];
} else {
$postdate = "NOW()";
}
if (isset($postDetailArray['tagString'])) {
$tagString = $postDetailArray['tagString'];
} else {
$tagString = "";
}
You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop() (and similar) all you like on it and won't affect anything outside. function sendemail($id, $userid){ // ... } sendemail(array('a', 'b', 'c'), 10);
Arguments that do not stop the function from working even though there is nothing passed to it are known as optional arguments. Arguments whose presence is completely optional, their value will be taken by the program if provided.
PHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call.
You can use an array of defaults and then merge the argument array with the defaults. The defaults will be overridden if they appear in the argument array. A simple example:
$defaults = array(
'foo' => 'aaa',
'bar' => 'bbb',
'baz' => 'ccc',
);
$options = array(
'foo' => 'ddd',
);
$merged = array_merge($defaults, $options);
print_r($merged);
/*
Array
(
[foo] => ddd
[bar] => bbb
[baz] => ccc
)
*/
In your case, that would be:
function addLinkPost($postDetailArray) {
static $defaults = array(
'title' => 'Error: No Title',
'url' => 'no url',
'caption' => '',
'publish' => true,
'postdate' => 'NOW()',
'tagString' => '',
);
$merged = array_merge($defaults, $postDetailArray);
$title = $merged['title'];
$url = $merged['url'];
$caption = $merged['caption'];
$publish = $merged['publish'];
$postdate = $merged['postdate'];
$tagString = $merged['$tagString'];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With