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

 ID:                 63818
 Comment by:         danielklein at airpost dot net
 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:

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)));
}
?>


Previous Comments:
------------------------------------------------------------------------
[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