Consider the following code:
preg_match('/(\d)(\d?)/', '1', $matches);
var_export($matches);
It outputs:
array (
0 => '1',
1 => '1',
2 => '',
)
So the optional [2]
entry is set, but is an empty string.
However, I remember in the past to have seen cases where an optional capturing group, when used last, is not set (the array would stop at [1]
).
Did I dream, or are there some cases where the entry can not be set?
I know I could use if (! isset($matches[2]) || $matches[2] == '')
if I want to be sure, but that would clutter the code needlessly.
It depends on whether you make the whole capturing group optional or not.
If you make the group required but allow it to match the empty string then the match will always be set, but might be empty:
preg_match('/(\d)(\d?)/', '1', $matches); // $matches[2] === ''
If you make the group optional by moving the quantifier ?
outside the brackets, the match will be set conditionally:
preg_match('/(\d)(\d)?/', '1', $matches); // no $matches[2]