php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #46596 Setting an associative array $var with the key $var: $var[$var] = true
Submitted: 2008-11-17 17:20 UTC Modified: 2009-12-23 10:27 UTC
From: benjaminNOpickSPAM at web dot de Assigned:
Status: Not a bug Package: Documentation problem
PHP Version: 5CVS, 6CVS (2008-11-24) OS: *
Private report: No CVE-ID: None
 [2008-11-17 17:20 UTC] benjaminNOpickSPAM at web dot de
Description:
------------
As the following lines are ok:

$var = $var + 1;
$var[trim($var2)] = '';

I expected PHP to first evaluate the $key-String ([$var]), then modify $var. So a line like:

$var = 'a';
$var[$var] = 0;

should work. 

Reproduce code:
---------------
<?php
$var = 'xxxxx';
$var[$var] = true;
var_dump($var);
?>

Expected result:
----------------
array(1) { ["xxxxx"]=>  bool(true) }

or a warning like:
Warning: Cannot use a scalar value as an array 

Actual result:
--------------
string(5) "1xxxx"

Depending on what code was before it, or what was in $var before, the first character is not always '1'.

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-11-18 23:31 UTC] jani@php.net
This is just side-effect of the fact that [] is also used for 
strings. It's not just for arrays.
 [2008-11-24 19:48 UTC] lbarnaud@php.net
Jani, this seems to be an expected behavior. The code basically does

$var[0] = "1";

And $var becomes "1xxxx".


 [2009-01-28 23:06 UTC] jani@php.net
You're quite right there. Reclassified.
 [2009-12-16 23:00 UTC] seld@php.net
I can't think of a sane place or way to describe this in the docs. It's clearly specified that strings support the square brackets already, therefore I'd recommend closing as Bogus.
 [2009-12-23 10:27 UTC] kalle@php.net
Jordi, I agree. Closed
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 17 14:04:04 2025 UTC