php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #63818 Need option to search in array keys instead of values
Submitted: 2012-12-20 17:06 UTC Modified: 2018-03-21 13:09 UTC
Votes:1
Avg. Score:3.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: dkadosh at affinegy dot com Assigned:
Status: Suspended Package: PCRE related
PHP Version: 5.3.20 OS: any
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2012-12-20 17:06 UTC] dkadosh at affinegy dot com
Description:
------------
---
From manual page: http://www.php.net/function.preg-grep
---
I'm asking for an extra flag to this function, to cause it to do its search in the array keys rather than in the values.

While there's a comment in the above page of how to "post-process" preg_grep() results to achieve this, I'd rather it be done in C (inside the PCRE code) than PHP for performance reasons.

I thought about something like this:
$a = array_flip( preg_grep('/Version$/', array_flip($aParams)) );

which would almost return what I want, HOWEVER it has two problems:
1) If certain values of $aParams are duplicated, the first array_flip() will "lose" those rows in the array.
2) I'd incur a sizeable CPU and memory hit by calling array_flip, which duplicates the array(s) in RAM.


Test script:
---------------
The current work-around:

function preg_grep_keys( $pattern, $input, $flags = 0 )
{
    $keys = preg_grep( $pattern, array_keys( $input ), $flags );
    $vals = array();
    foreach ( $keys as $key )
    {
        $vals[$key] = $input[$key];
    }
    return $vals;
}



Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-03-14 22:52 UTC] danielklein at airpost dot net
How about this?

<?php
function preg_grep_keys($pattern, $input, $flags = 0) {
    return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
?>
 [2013-04-01 13:45 UTC] dkadosh at affinegy dot com
@danielklein: Yes, that's definitely more efficient than my work-around function, 
thanks.
However, it is not as efficient as having it done entirely in C per my original 
request, as your solution still involves partially duplicating the original array, 
etc.  My use case involves processing pretty high volumes of data, so the arrays 
can be quite large (~5K items), and this function being called several million 
times a day.
 [2018-03-21 13:09 UTC] cmb@php.net
-Status: Open +Status: Suspended
 [2018-03-21 13:09 UTC] cmb@php.net
This feature appears to be controversial, and as such would
require the RFC process[1].  Anybody is welcome to start it! For
the time being, I'm suspending this ticket.

[1] <https://wiki.php.net/rfc/howto>
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Apr 20 04:01:28 2024 UTC