Should you initialize $ match before calling preg_match?

preg_matchtakes an argument $matchesas a reference. All the examples that I saw do not initialize it before they are passed as an argument. Like this:

preg_match($somePattern, $someSubject, $matches);
print_r($matches);

Isn't that error prone? What if it $matchesalready contains a value? I think it should be initialized with an empty array before passing it as an argument. Like this:

$matches = array();
preg_match($somePattern, $someSubject, $matches);
print_r($matches);

Am I just paranoid?

+4
source share
2 answers

There is no need to initialize $ match, as it will be updated with the results. This is actually the second return value from the function.

+5
source

, $matches. , , :

$somePattern = '/123(456)/';
if (preg_match($somePattern, $someSubject, $matches)) {
    print_r($matches[1]);
}

undefined . isset($matches[1]) .

+1

Source: https://habr.com/ru/post/1541623/


All Articles