PHP Difference between array() and []

PhpArraysSyntaxSquare Bracket

Php Problem Overview


I'm writing a PHP app and I want to make sure it will work with no errors.

The original code:

<?php
$data = array('name' => 'test',
              'id'   => 'theID');

echo form_input($data);
?>

Would the following work with no errors or is not recommended for some reason?

<?= form_input(['name' => 'test', 'id' => 'theID']); ?>

Are there any difference?

I've looked again the data about array() and the short array method with square brackets [] in PHP.net but I'm not sure.

And also, is the short php tag <?= ?> fine for echoing? Is there any version issue? (provided is enabled in php.ini)

Php Solutions


Solution 1 - Php

Following [] is supported in PHP >= 5.4:

['name' => 'test', 'id' => 'theID']

This is a short syntax only and in PHP < 5.4 it won't work.

Solution 2 - Php

As of 2022, it has been 10 years since the [] syntax was added. That is long enough to drop array() except in old legacy programs, in my opinion.

Solution 3 - Php

If you are using 5.3 or previous version then you can't use [] as an array as well as associative array. If you are using 5.4 or later version of PHP then you can use either array() or [] to create an array, associative array or even multidimensional array.

Solution 4 - Php

And regarding the <?= ?> part of the question: it is largely not frowned upon, at least not in 2019.

  1. A good technical breakdown: https://softwareengineering.stackexchange.com/questions/151661/is-it-bad-practice-to-use-tag-in-php
  2. A note in PSR-1: Files MUST use only <?php and <?= tags.
  3. TL;DR: There is no reason you cannot or should not use it.

Solution 5 - Php

Using php 7.2, for me it seems rather then [I am a an array] {I am an array seems to work}. Difference is between {} and []. My code

<p>
  <label for="post_category"> Cat 1 </label>
  <input type="checkbox" name="post_category{first}" value="cat1">
  <br />
  <label for="post_category{second}"> Cat 2 </label>
  <input type="checkbox" name="post_category" value="cat2">
</p>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMr.WebView Question on Stackoverflow
Solution 1 - PhpThe AlphaView Answer on Stackoverflow
Solution 2 - PhpDavid SpectorView Answer on Stackoverflow
Solution 3 - PhpMd. A. BarikView Answer on Stackoverflow
Solution 4 - PhpAydin4ikView Answer on Stackoverflow
Solution 5 - PhpMahad AliView Answer on Stackoverflow