php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #78693 @ operator evaluates @$foo['undefined'] to $foo[0] on strings
Submitted: 2019-10-18 20:14 UTC Modified: 2019-10-18 20:59 UTC
From: david at vielhuber dot de Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 7.3.10 OS: Ubuntu 18
Private report: No CVE-ID: None
 [2019-10-18 20:14 UTC] david at vielhuber dot de
Description:
------------
$foo = 1337;

@$foo['undefined'] // evaluates to null

$foo = '1337';

@$foo['undefined'] // evaluates to '1'

Desired behaviour: @$foo['undefined'] should also evaluate to null.


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2019-10-18 20:22 UTC] requinix@php.net
-Status: Open +Status: Not a bug -Package: Unknown/Other Function +Package: *General Issues
 [2019-10-18 20:22 UTC] requinix@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

The @ operator is not changing the behavior. All it does here is hide notices and warnings from you. If you were able to see those then you might understand that using [] on an integer is not the same as using it on a string.

$foo = 1337;
$foo['undefined'];
> Notice: Trying to access array offset on value of type int

$foo = '1337';
$foo['undefined'];
> Warning: Illegal string offset 'undefined'

Since string offsets are supposed to be integers, PHP coerces 'undefined' to 0.
 [2019-10-18 20:42 UTC] david at vielhuber dot de
That was quick, thank you very much for the explanation.
Any chance this coercion gets changed?
 [2019-10-18 20:59 UTC] requinix@php.net
The coercion is necessary so that PHP can support numeric string offsets ($foo['1']). PHP already issues a warning when the string is not valid, and that's the most severe action it can take while still allowing code to execute.

Don't use @.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 21 14:01:32 2024 UTC