Dev Newb
Dev Newb

Reputation: 565

PHP preg_match creating empty arrays

I am using the following code:

foreach ($_POST as $key => $value) {
    (preg_match("/^._box_(\d+)_5$/", $key, $matches));
    //$prodid[] = $matches[1];
    $firephp->log($matches, 'matches');
    };

This code is working on the following information being $_POSTed from the previous page:

array(
['clin'] =>
['clinmail'] =>
['quest_3'] =>
['quest_7'] =>
['quest_8'] =>
['quest_9'] =>
['quest_10'] =>
['quest_15'] =>
['quest_16'] =>
['hosp'] => 8
['user'] => 16
['a_box_15_5'] => 2
['a_box_16_5'] => 2
['b_box_1_5'] => '$0.00'
['b_box_29_5'] => 1
)

The problem is I get the following result:

matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array('0'=>'a_box_15_5', '1'=>'15')
matches: array('0'=>'a_box_16_5', '1'=>'16')
matches: array('0'=>'b_box_1_5', '1'=>'1')
matches: array('0'=>'b_box_29_5', '1'=>'29')

I don't want it matching the first 11 positions. I only want the results that actually match what I'm looking for, which in this case is that last four $_POST's isn't that what preg_match is supposed to do? How can I limit it to just the matches?

Upvotes: 0

Views: 1421

Answers (2)

rid
rid

Reputation: 63442

preg_match() works correctly: if there are no matches, $matches will be empty. But you're not doing anything different if there are no matches, you're always calling $firephp->log(), matches or not.

preg_match() returns 1 if the pattern matches, or 0 otherwise and false if an error occurred, so you can use that to see if there are matches, and only then call $firephp->log():

foreach ($_POST as $key => $value) {
    if (preg_match('/^._box_(\d+)_5$/', $key, $matches)) {
        $firephp->log($matches, 'matches');
    }
}

Upvotes: 3

ariefbayu
ariefbayu

Reputation: 21979

add check before logging it:

foreach ($_POST as $key => $value) {
    (preg_match("/^._box_(\d+)_5$/", $key, $matches));
    //$prodid[] = $matches[1];
    if(!empty($matches)){
        $firephp->log($matches, 'matches');
    }
};

Upvotes: 1

Related Questions