Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abbreviation for PHP's array()

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?

like image 473
Meisner Avatar asked Dec 08 '25 08:12

Meisner


2 Answers

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]]

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.

like image 27
Alex Barrett Avatar answered Dec 09 '25 21:12

Alex Barrett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!