php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #79850 array_walk / array_filter incorrectly warn variables should be passed by ref
Submitted: 2020-07-13 12:21 UTC Modified: 2020-07-15 07:48 UTC
From: sjon@php.net Assigned: sjon (profile)
Status: Closed Package: Arrays related
PHP Version: 8.0.0alpha2 OS: archLinux
Private report: No CVE-ID: None
 [2020-07-13 12:21 UTC] sjon@php.net
Description:
------------
I'm not 100% sure this is a bug but both array_walk and array filter throw warnings when variables are passed by reference. Either the message is inverted (they don't accept variables by reference) or it's incorrectly thrown

Originally found as https://3v4l.org/WH94Q

Test script:
---------------
$ids = array("8479");

$newIds = array_filter($ids, function(&$n) {
                $n = intVal($n);
            });


Expected result:
----------------
no warning

Actual result:
--------------
Warning: {closure}(): Argument #1 ($n) must be passed by reference, value given in /in/WH94Q on line 7

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-07-13 12:54 UTC] nikic@php.net
This is an intentional change, now documented with https://github.com/php/php-src/commit/2edc5e00ac5ceef6429c3ef4651745efa97a13d8.

As the the inverted message, I can see where you're coming from there... The message appears because array_filter() internally calls the callback with a value, but the function expects a reference, thus the warning in this form.
 [2020-07-14 12:42 UTC] sjon@php.net
Aha, so this fix would be for the user to write 

```
$newIds = array_filter($ids, function($n) {
    return intval($n);
});
```

or in this case, simply `$newIds = array_filter($ids, 'intval');`.

Does the same reasoning apply to https://3v4l.org/ZCgRe ? It seems internal functions that accept references will function correctly but still throw the same warning.
 [2020-07-15 07:48 UTC] sjon@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: sjon
 [2020-07-15 07:48 UTC] sjon@php.net
For https://3v4l.org/ZCgRe, instead of array_shift/array_pop, reset/end should have been used as they return the same value but don't modify the original value.

This message will probably confuse more users
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 17:01:29 2024 UTC