Edit report at https://bugs.php.net/bug.php?id=63818&edit=1

 ID:                 63818
 User updated by:    dkadosh at affinegy dot com
 Reported by:        dkadosh at affinegy dot com
 Summary:            Need option to search in array keys instead of
                     values
 Status:             Open
 Type:               Feature/Change Request
 Package:            PCRE related
 Operating System:   any
 PHP Version:        5.3.20
 Block user comment: N
 Private report:     N

 New Comment:

@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.


Previous Comments:
------------------------------------------------------------------------
[2013-03-14 22:52:11] 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)));
}
?>

------------------------------------------------------------------------
[2012-12-20 17:06:30] 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;
}




------------------------------------------------------------------------



-- 
Edit this bug report at https://bugs.php.net/bug.php?id=63818&edit=1

Reply via email to