Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

syntax

php

What is the shorthand for array notation in PHP?

I tried to use (doesn't work):

$list = {}; 

It will be perfect, if you give links on some information about other shorthands for PHP.

like image 822
James Avatar asked Nov 24 '10 21:11

James


People also ask

What is short array syntax?

Short array syntax was introduced in PHP 5.4 and was added to the Drupal code standards for Drupal 8. Short array syntax is cleaner and is consistent with other programming languages, such as Python. It is also easier to see closing array statement from the closing brackets of a function.

Is array an element in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.


1 Answers

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";
like image 149
Alin Purcaru Avatar answered Sep 20 '22 07:09

Alin Purcaru