|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #8794 preg_grep changed behavior by design?
Submitted: 2001-01-18 20:27 UTC Modified: 2001-03-08 10:22 UTC
From: instigator at openave dot com Assigned:
Status: Closed Package: PCRE related
PHP Version: 4.0.4pl1 OS: GNU/Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
Solve the problem:
42 - 15 = ?
Subscribe to this entry?

 [2001-01-18 20:27 UTC] instigator at openave dot com

# The behavior of preg_grep() changed, seems to be broken.
# Don't know if it is a preg_grep() change or a Zend hash change.
# Indexing bug is my guess, or RedHat 7.0.
# Or maybe by design (see NEWS)
# Here is a test case for reproduction.

# Set up an array of strings.
$a = array( "foo", "bar", "baz" );

# Display them all first, FYI.
for( $bug = 0; $bug < count( $a ); $bug++ )
        echo "test: ".$a[$bug]."<br>";

# This works as expected, [0] is result, [1] is whatever.
$b = preg_grep( "/^foo/", $a );
echo "try to find foo as [0]: ".$b[0]."   count=".count( $b )."<br>";
echo "try to find foo as [1]: ".$b[1]."   count=".count( $b )."<br>";

# This fails as unexpected, [0] is whatever, [1] is result????
$b = preg_grep( "/^bar/", $a );
echo "try to find bar as [0]: ".$b[0]."   count=".count( $b )."<br>";
echo "try to find bar as [1]: ".$b[1]."   count=".count( $b )."<br>";



Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2001-01-19 09:01 UTC]
Yes, preg_grep() was always supposed to return the results with their original keys but it wasn't until the behavior was fixed a little while ago.

 [2001-01-19 11:35 UTC] instigator at openave dot com
The behavior is inconsistent with expectations and breaks code.

In the example given count() returns 1, so loops attempting to access found elements won't work.

preg_grep() now determines and then discards indexes, forcing the caller
to reconstruct 'valid' indexes (using the count() of the original array and comparisons to "").

If this is the preferred approach I suggest returning an array of indexes, not a half baked array of strings.

 [2001-03-08 10:22 UTC]
Manual says that the behaviour of preg_grep is exaclty what
it is. You can use each() or foreach() to go through the
array, count() is not sacred in any way (and also is slower
and error-prone, since nobody warrants you that array
elements are in sequential order). 
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Tue Oct 26 03:03:35 2021 UTC