Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you initialize $matches before calling preg_match?

Tags:

regex

php

preg_match accepts a $matches argument as a reference. All the examples I've seen do not initialize it before it's passed as an argument. Like this:

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

Isn't this error-prone? What if $matches already contains a value? I would think it should be initialized to an empty array before passing it in as an arg. Like this:

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

Am i just being paranoid?

like image 360
dellsala Avatar asked May 22 '14 14:05

dellsala


People also ask

Which of the following call to Preg_match will return true?

The preg_match() function returns true if pattern matches otherwise, it returns false.

What is the difference between Preg_match and Preg_match_all?

preg_match stops looking after the first match. preg_match_all , on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.

Which of the following call to Preg_match will return false?

preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .

What is the purpose of Preg_match () regular expression in PHP?

The preg_match() function will tell you whether a string contains matches of a pattern.


2 Answers

There is no need to initialise $matches as it will be updated with the results. It is in effect a second return value from the function.

like image 57
Chris Lear Avatar answered Oct 12 '22 19:10

Chris Lear


as Chris Lear said you don't need to initialize $matches. But if your pattern contains a capture group you want to use later, it is better to write:

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

to avoid the error of undefined index in the result array. However, you can use isset($matches[1]) to check if the index exists.

like image 45
Casimir et Hippolyte Avatar answered Oct 12 '22 19:10

Casimir et Hippolyte