Shorthand for Arrays: Is There a Literal Syntax Like {} or []

Shorthand for arrays: is there a literal syntax like {} or []?

Update:
As of PHP 5.4.0 a shortened syntax for declaring arrays has been introduced:

$list = [];

Previous Answer:

There isn't. Only $list = array(); But you can just start adding elements.

<?php
$list[] = 1;
$list['myKey'] = 2;
$list[42] = 3;

It's perfectly OK as far as PHP is concerned. You won't even get a E_NOTICE for undefined variables.

E_NOTICE level error is issued in case
of working with uninitialized
variables, however not in the case of
appending elements to the
uninitialized array.

As for shorthand methods, there are lots scattered all over. If you want to find them just read The Manual.

Some examples, just for your amusement:

  1. $arr[] shorthand for array_push.
  2. The foreach construct
  3. echo $string1, $string2, $string3;
  4. Array concatenation with +
  5. The existence of elseif
  6. Variable embedding in strings, $name = 'Jack'; echo "Hello $name";

Javascript - Are all arrays literal?

An array is a type of value (it can be stored in variables, passed to functions, etc).

An array literal is a type of syntax. Specifically it refers to [ ... ] (where ... is a comma-separated list of values).

Executing an array literal creates an array at runtime. However, there are other ways to create arrays:

var x = new Array();

x contains an array that was not created from a literal.

Similarly, there are all kinds of operations that produce strings, but only "..." and '...' are string literals.

Is there a shorthand notation for initialising associative arrays or objects in PHP, like the one introduced to JavaScript with ES2015?

As you did it in JS, you can collect all variables by their names in array and do compact():

$a = 'foo'; $b = 'bar'; $c = 'baz';

$ar=['a','b','c'];
print_r(compact($ar));

Output:

Array
(
[a] => foo
[b] => bar
[c] => baz
)

Or just do compact('a', 'b', 'c'); as well.

Demo

what is [] operator in Ruby

It depends if you're talking about array literals or those brackets used for getting or assigning values from/to arrays or hashes.

As a literal, [] is just an array literal, shorthand for writing Array.new. You also asked about {}, which is a hash literal, i.e. shorthand for writing Hash.new. Parentheses are not literals (or 'operators' for that matter) – they're used to group things.

As an 'operator' for getting or assigning values, as others have pointed out in the comments, [] isn't special or conceptually different from other 'operators'.

In the same way 2 + 3 is sugar for writing 2.+(3), writing array[0] is sugar for writing array.[](0).

The reason this works is that arrays have a method that's literally called []. You can find it by getting all the methods on an array:

[].methods
# => long array including :[] (and also :[]=, by the way, for assignments)

Note that the brackets in [].methods are an array literal, not an 'operator'.

I haven't looked at the implementation of any Ruby interpreters, but my guess is they see something like array[0] and convert it to array.[](0) (or at least they treat it as such). That's why this kind of sugar syntax works and looks like 'operators' even though it's all methods under the hood.

What does %w(array) mean?

%w(foo bar) is a shortcut for ["foo", "bar"]. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.

Is there any difference between these three ways of creating an array?

Using [] is more secure and reliable than using new Array(). The former is actually recommended. This is because the value of Array can be overridden. Also, [] is faster compared to new Array().

Take a look at these related questions:

  • What’s the difference between “Array()” and “[]” while declaring a JavaScript array?
  • JSLint: “Use the array literal notation []” for var os_map = {}
  • What's wrong with var x = new Array();
  • Is JavaScript 's “new” Keyword Considered Harmful?

A related link:

  • JSLint wants you to avoid new.

To clarify what "overridden" means, you can do something like this:

function Array() {
alert("I am not really an array! BWAHAHAHAHAHA!");
}

Now when you do new Array(); you will get an alert, which is obviously not what you want.

In short, there really is no pressing need to to use new Array() and it doesn't buy you anything more compared to using the literal [].

Array Type VS Type[] in Typescript

There isn't any semantic difference

There is no difference at all. Type[] is the shorthand syntax for an array of Type. Array<Type> is the generic syntax. They are completely equivalent.

The handbook provides an example here. It is equivalent to write:

function loggingIdentity<T>(arg: T[]): T[] {
console.log(arg.length);
return arg;
}

Or:

function loggingIdentity<T>(arg: Array<T>): Array<T> {
console.log(arg.length);
return arg;
}

And here is a quote from some release notes:

Specifically, number[] is a shorthand version of Array<number>, just as Date[] is a shorthand for Array<Date>.

About the readonly type modifier

TypeScript 3.4, introduces the readonly type modifier. With a precision:

the readonly type modifier can only be used for syntax on array types and tuple types

let err2: readonly Array<boolean>; // error!    
let okay: readonly boolean[]; // works fine

The following declaration is equivalent to readonly boolean[]:

let okay2: ReadonlyArray<boolean>;

Shorthand for arrays: is there a literal syntax like {} or []?

Update:
As of PHP 5.4.0 a shortened syntax for declaring arrays has been introduced:

$list = [];

Previous Answer:

There isn't. Only $list = array(); But you can just start adding elements.

<?php
$list[] = 1;
$list['myKey'] = 2;
$list[42] = 3;

It's perfectly OK as far as PHP is concerned. You won't even get a E_NOTICE for undefined variables.

E_NOTICE level error is issued in case
of working with uninitialized
variables, however not in the case of
appending elements to the
uninitialized array.

As for shorthand methods, there are lots scattered all over. If you want to find them just read The Manual.

Some examples, just for your amusement:

  1. $arr[] shorthand for array_push.
  2. The foreach construct
  3. echo $string1, $string2, $string3;
  4. Array concatenation with +
  5. The existence of elseif
  6. Variable embedding in strings, $name = 'Jack'; echo "Hello $name";

What does [] mean in JavaScript?

it is an array literal. It is not quite the same as declaring new Array() - the Array object can be overwritten in JavaScript, but the array literal can't. Here's an example to demonstrate

// let's overwrite the Array object
Array = function(id) {
this.id = id;
}

var a = new Array(1);
var b = [];

console.log(a.hasOwnProperty("id")); // true
console.log(b.hasOwnProperty("id")); // false

console.log(a.push); // false, push doesn't exist on a
console.log(b.push); // true, but it does on b

b.push(2);
console.log(b); // outputs [2]


Related Topics



Leave a reply



Submit