views:

155

answers:

2

Howdy,

To pass variables into functions, I do the following (as other people I'm sure):

function addNums($num1, $num2)
{
    $num1 + $num2;
}

addNums(2, 2);

My question is how would I structure a function to act like Wordpress:

wp_list_categories('title_li=');

Essentially I am looking for a way to create a key/value pair in my functions. Any advice is appreciated.

+5  A: 

parse_str() should do what you want: http://www.php.net/parse_str

MSpreij
+2  A: 

You can use parse_str to parse the string for arguments. The tricky thing is that you may not want to just allow any and all parameters to get passed in. So here's an example of only allowing certain parameters to be used when they're passed in.

In the following example, only foo, bar and valid would be allowed.

function exampleParseArgs($arg_string) {
    // for every valid argument, include in
    // this array with "true" as a value
    $valid_arguments = array(
     'foo' => true,
     'bar' => true,
     'valid' = true,
    );
    // parse the string
    parse_str($arg_string, $parse_into);
    // return only the valid arguments
    return array_intersect_key($parse_into,$valid_arguments);

}

baz will be dropped because it is not listed in $valid_arguments. So for this call:

print_r(exampleParseArgs('foo=20&bar=strike&baz=50'));

Results:

Array
(
    [foo] => 20
    [bar] => strike
)

Additionally, you can browse the Wordpress Source code here, and of course by downloading it from wordpress.org. Looks like they do something very similar.

artlung
Perfect! - thanks
Keith Donegan