1

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.

6
  • Are you looking for something like "return $array[$param1] = $param2;"? Sorry not a wordpress expert.. Btw. I would suggest giving each parameter a distinct name! Commented Jun 22, 2009 at 22:57
  • I don't know if that addNums example would work correctly... Commented Jun 22, 2009 at 22:58
  • Here is a link to the API for wp_list_categories() codex.wordpress.org/Template_Tags/wp_list_categories Commented Jun 22, 2009 at 23:01
  • 1
    In my answer below I point to an online copy of the WP source: phpxref.com/xref/wordpress/wp-includes/… Commented Jun 23, 2009 at 1:11
  • 1
    Also, the reason for using a string like this would be to allow named variables in a compact manner. Commented Jun 23, 2009 at 1:13

2 Answers 2

6

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

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

Comments

3

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.

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.