2

I don't know how about you, but I'm not very fond of the way arrays are constructed in PHP. I have this feeling that I use array keyword way too often and that array($k => $v) or e.g. array($k1=>array($k2=>$v)) are way too long given usefulness of maps. (Moreover, recently I've learned JS way of doing it and now I really am jealous)

The best I could come up with to remedy this is:

function a() { // array
  return func_get_args();
}

and

function h() { // hash
  $array=array();
  for($i=0; $i<func_num_args()-1; $i+=2) {
    $array[func_get_arg($i)]=func_get_arg($i+1);
  }
  return $array;
}

...but they don't permit using => operator.

Any other ideas?

Community
  • 1
  • 1
Meisner
  • 775
  • 11
  • 18
  • 1
    Arrays in PHP have never really felt like arrays to me. An array to me is a strictly one-dimensional keyless list of elements. Oh well.. – Nick Bedford Sep 29 '09 at 23:53

3 Answers3

8

Starting in PHP 5.4, a shorthand syntax for arrays is supported using [ and ]. Your examples:

array($k => $v)
array($k1=>array($k2=>$v))

can now be written as:

[$k => $v]
[$k1 => [$k2 => $v]]
3

There is no shorthand syntax for declaring arrays in PHP. It's a feature I would like to see, but I very much doubt it will happen.

It's been discussed a lot by the PHP developers and the PHP community, but it was never implemented. A good starting point if you want to see how the discussion unfolded is available on the PHP wiki: http://wiki.php.net/rfc/shortsyntaxforarrays

For now, you will have to put up with typing a handful of extra characters.

Alex Barrett
  • 16,175
  • 3
  • 52
  • 51
0

Use Texter or any decent editor with templates/macros. E.g.:

[]+Tab ---> array({cursor})

If you're truly obsessed, make a json_decode macro to run a selection through this:

<?php var_export(json_decode(stream_get_contents(STDIN), true));

Just don't put JSON in your PHP code because you'd rather look at JSON...

Steve Clay
  • 8,671
  • 2
  • 42
  • 48