Here\'s what I am trying to accomplish:
function foo($args) {
switch($args[\'type\']) {
case \'bar\':
bar($args[\'data\']); // do something
break;
There are no alternatives to constructing these nested arrays-- but there are options in how you can format your code that makes it readable. This is strictly 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'
);
No. Alternative syntaxes for creating arrays have been proposed several times (the link lists 5 separate threads in the dev mailing list), but they were rejected.
No, there is no "short-syntax" to write arrays nor objects, in PHP : you have to write all those array()
.
(At least, there is no such syntax... yet ; might come in a future version of PHP ; who knows ^^ )
But note that have too many imbricated arrays like that will makes things harder for people who will have to call your functions : using real-parameters means auto-completion and type-hinting in the IDE...
You could create a JSON-encoded string and use json_decode()
to convert it into a variable. This has syntax 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 accommodate @therefromhere's suggestion.