tags:

views:

104

answers:

3

Is there a way to use the PHP => operator (?) without using the array() "constructor"?

To be specific, I want to create a function that will get a list of keys and values without wrapping it into an array:

function keysAndValues($items) {
    /* ... */
}

keysAndValues(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);

Instead of

keysAndValues(array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
));

Is there a way to do this?

+4  A: 

These would be named arguments. Nope, not possible in PHP. You will have to wrap an array() around them.

If it's not the array that's bothering you but the fact that you have to work with an array inside the function, try

function my_function($array)
{
extract($array);
...
if (isset($number)) echo "Number is: ".$number;
}

to unpack the options into the function's scope:

my_function(array("number" => "one")); // Will output "Number is: one"

it saves the hassle of unpacking them one by one using foreach().

Pekka
Named arguments! that's the one. That got me into this bug report http://bugs.php.net/bug.php?id=22216 which says PHP development team declined it. Thank you.
LiraNuna
'If it's not the array that's bothering you' - actually it is, because my goal is a type of dictionary class. I was wondering if there's a better way to send variables to the constructor.
LiraNuna
A: 

well, specifically, the '=>' operator denotes the key, value pair inside an array, so there's really no reason to use it outside the array constructor.

that said, it is used inside things like a 'foreach' loop to grab the key and value for each item in an array

foreach ($arr as $key=>$val)
contagious
+1  A: 

The closest thing you can get to what you want is by using dynamic arguments.

Using this tutorial/overview as a base, here is a hack to provide a potential solution:

function keysAndValues() {
   for($i = 0 ; $i < func_num_args(); $i++) {
       list($key, $value) = explode('=>', func_get_arg($i));
       // Do something with the $key and $value
   }
}

It would then be called like this:

keysAndValues('key1=>value1','key2=>value2','key3=>value3');
keysAndValues('key1=>value1');

Basically, you can have any amount of parameters... they are dynamic!

Doug Neiner
Wow, that's hacky. The biggest problem with this is that you'll only be able to pass strings, which can't even contain `'=>'`. It would be better (and less code) to just use arrays here. Nice hack though. :oP
deceze
Haha.. sure is :) However, he listed all his keys as strings... so as long as they don't contain `=>`
Doug Neiner