php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #73735 array_column keys should be preserved
Submitted: 2016-12-13 21:27 UTC Modified: 2016-12-14 03:23 UTC
From: photon0 at gmail dot com Assigned:
Status: Open Package: Arrays related
PHP Version: Next Minor Version OS: ANY
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: photon0 at gmail dot com
New email:
PHP Version: OS:

 

 [2016-12-13 21:27 UTC] photon0 at gmail dot com
Description:
------------
It would increase the usability of this function if it could preserve the array's keys in the result.
I was expecting this to be the default behaviour.

best regards,
David Lévêsque

Test script:
---------------
$items = array(
    1 => ["id" => 1],
    2 => ["id" => 4],
    3 => ["id" => 9],
    "four" => ["id" => 16]
);

var_dump(array_column($items,"id"));

Expected result:
----------------
array(4) { [0]=> int(1) [1]=> int(4) [2]=> int(9) ["four"]=> int(16) }

Actual result:
--------------
array(4) { [0]=> int(1) [1]=> int(4) [2]=> int(9) [3]=> int(16) }

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-12-14 03:23 UTC] requinix@php.net
As default behavior it makes sense, but it should be possible to explicitly invoke the behavior using arguments and I'm not sure how the change could be squeezed into the function. NULL as the $index_key?

Anyway, the workaround is trivial:
  array_combine(array_keys($items), array_column($items, "id"))
 [2016-12-14 15:30 UTC] photon0 at gmail dot com
I always saw PHP's arrays as a Swiss army knife for data manipulation. If you say this would be difficult to implement or would result in less than optimal performance I refer entirely to your judgment.
The only disadvantage I see to the workaround is the performance. Calling 3 functions is clearly slower than using just one.

That said, your point is valid and this request was just a suggestion.
 [2021-02-18 17:27 UTC] php at yopmail dot com
I guess you even meant:

Expected result:
----------------
array(4) { [1]=> int(1) [2]=> int(4) [3]=> int(9) ["four"]=> int(16) }

(i.e. keep all keys, even numeric)

and I agree with you! (and a quick Web search shows we're not alone...)

---

@requinix: I see at least 2 ways:

  1. Add a `bool $preserve_keys = false` parameter (like array_slice)
that would at least enable us to use
    array_column($items, "id", null, true)

  2. Change the default behavior (consistent with array_map)
and just use
    array_values(array_column($items, "id"))
if you really want to lose the keys


PS: see also Request #66435
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 21 15:01:29 2024 UTC