The use of preg_match return value

Published Feb 18, 2018

When learning what preg_match function does, I was expected return value from it.
That surprised me, since all native functions I use return a data, almost.
Getting back to preg_match documentation on php.net I can see that there is & sign on the third parameter.
It means that the variable passed to the function is a reference so that we will expect a modification from the function to the variable outside of it.

Yes, of course, it returns a value, but it's not the kind of value I need in order to work properly.

Here is an example

$pattern = "/@/";
$subject = "me@gmail.com";
$matches = [];

preg_match($pattern, $subject, $matches);
var_dump($matches);
/* result
array(1) {
  [0]=>
  string(1) "@"
}
*/

As you can see, preg_match has changed my empty array.

Discover and read more posts from Bart ehui
get started