1

PHP array()[]= fails:

<?php
// PHP Version => 5.6.13
$e=array()[]=1;       // REJECTED "E_COMPILE_ERROR : type 64 -- Cannot use [] for reading "
$d=array();$e=$d[]=1; // Workaround - accepted

despite the manual saying that array() returns an array and that somearray[]= assigns a value to an array.

Why?

ChrisJJ
  • 2,191
  • 1
  • 25
  • 38
  • 3
    *"An **existing** array can be modified by explicitly setting values in it."* In your first example your array does not exist yet. – Rizier123 Nov 11 '16 at 01:59
  • It does. array() creates it, it exists, and then [] attempts to access it. – ChrisJJ Nov 19 '16 at 12:59

1 Answers1

1

array() is a language construct, not a function. it doesn't actually return an array like a function does, it creates an array internally, which is a temporary expression. You have to assign it to a variable first to interact with the array.

PHP7 has a better error for this

Fatal error: Cannot use temporary expression in write context

Community
  • 1
  • 1
Machavity
  • 30,841
  • 27
  • 92
  • 100
  • "it doesn't actually return an array like a function does". It is however defined to return an array (see the docs I quoted), and that should be sufficient, regardless of whether this is 'like a function does'. Hence I conclude there's a bug - a failure of behaviour and documentation to accord. – ChrisJJ Nov 19 '16 at 12:58
  • @ChrisJJ It's not a bug … saying that as a core contributor to the PHP engine here. You cannot use arbitrary expressions where a variable-like value is expected. Variable-like values are function calls, property and array dereferences of other variable-like values. – bwoebi Nov 21 '16 at 15:10
  • "It's not a bug. You cannot use arbitrary expressions where a variable-like value is expected." That does not accord with the published language spec. The language spec doesn't say a variable-like value is required here. – ChrisJJ Nov 29 '16 at 16:03
  • "PHP7 has a better error for this. Fatal error: Cannot use temporary expression in write context" I can't imagine why you think this is better. Or even appropriate. array() is not a temporary expression. It's permanently there in the source, as might be e.g. myfunc(), 1+1. – ChrisJJ Nov 29 '16 at 16:07