PHP: less ugly syntax for named parameters / arrays?

Here is what I am trying to accomplish:

function foo($args) { switch($args['type']) { case 'bar': bar($args['data']); // do something break; } } // or something like that 

This is basically a way to use named parameters in PHP.

Now, to build this $args array, I have to write ugly syntax, for example:

 $builtArgs = array('type' => 'bar', 'data' => array(1, 2, 3), 'data2' => array(5, 10, 20) ); foo($builtArgs); 

Which gets uglier when I add more dimensions to the array, and also makes me write tons of array(...) constructs. Is there a nicer way to do this?

On the one hand, this could be done if we could use syntax like Python:

 $buildArgs = {'type' : 'bar', 'data' : [1, 2, 3], 'data2' : [5, 10, 20]}; 

But this is PHP.

+3
syntax coding-style php
source share
4 answers

You can create a JSON encoded string and use json_decode() to convert it to a variable. This syntax is very similar to the Python-like syntax you mentioned.

 $argstr = '{"type" : "bar", "data" : [1, 2, 3], "data2" : [5, 10, 20]}'; $buildArgs = json_decode($argstr, true); 

EDIT: Updated code to host @therefromhere's offer.

+6
source share

Not. Alternative syntaxes for creating arrays have been proposed several times (the link contains 5 separate threads on the Dev mailing list), but they were rejected.

+2
source share

No, there is no short syntax for writing arrays or objects in PHP: you need to write all those array() .
(At least there is no such syntax yet ... may appear in a future version of PHP, who knows ^^)

But note that too many fixed arrays like this will make it difficult for people who have to call your functions: using real parameters means automatic completion and type hint in the IDE ...

+2
source share

There is no alternative for building these nested arrays - but there are options in how you can format the code that makes it readable. This is strictly a preference:

 return array ( 'text' => array ( 'name' => 'this is the second', 'this' => 'this is the third', 'newarr' => array ( 'example' ), ) ); // Or using the long way $array = array(); $array += array ( 'this' => 'is the first array' ); 
+2
source share

All Articles