|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #17090 Getting slices of associative arrays
Submitted: 2002-05-08 06:04 UTC Modified: 2017-10-23 01:08 UTC
Avg. Score:3.5 ± 0.9
Reproduced:1 of 1 (100.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: chs at baltic-online dot de Assigned: kalle (profile)
Status: Closed Package: Arrays related
PHP Version: 4.2.0 OS: Solaris 5.8
Private report: No CVE-ID: None
 [2002-05-08 06:04 UTC] chs at baltic-online dot de

unless I have overlooked something, there seems to be no easy way to get a slice of an associative array based on certain keys. I would like to be able to do something like the following:

$array["a"] = 1;
$array["b"] = 2;
$array["c"] = 3;

$slice = hash_slice($array, array("a", "c"));

which would result in $slice becoming an array containing the values 1 and 3, associated with the keys a and c, respectively.

If something like this already exists, I'd be happy if you could let me know; otherwise, I'd like to suggest this as a feature for a future version of PHP. Thank you!


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2011-01-01 00:40 UTC]
-Package: Feature/Change Request +Package: Arrays related
 [2017-03-17 23:01 UTC]
A bit heavy perhaps, but:

$array = array_filter($array, function ($k) { return in_array($k, ['a', 'c']); }, ARRAY_FILTER_USE_KEY);

I'd probably be a bit hesitant to add such a task-specific utility function to the core, tbqh.
 [2017-10-23 01:08 UTC]
-Status: Open +Status: Closed -Assigned To: +Assigned To: kalle
 [2017-10-23 01:08 UTC]
This can easily be implemented in userland:

However for any future reader that would propose this to be a part of the core, the best way around it would be to submit a PR and mail internals@, as our array functions are already quite large
PHP Copyright © 2001-2018 The PHP Group
All rights reserved.
Last updated: Mon Oct 22 09:01:25 2018 UTC