0

Can you please explain documentation syntax in functions. For example php function

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

So far i understand that in in round brackets goes function's parameters,also that square bracket means for array. But what does that mean [, and why there are no comma after $subject?

Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34
ogbofjnr
  • 1,688
  • 5
  • 19
  • 41
  • 2
    [Documentation of how to read documentation.](http://php.net/manual/en/about.prototypes.php) – MonkeyZeus Aug 14 '18 at 13:04
  • If you want a real challenge then check out the function definition for [array_diff_uassoc()](http://php.net/manual/en/function.array-diff-uassoc.php) – MonkeyZeus Aug 14 '18 at 13:11
  • `[]` in php documentation (and in many other docs) is used to specify optionnal parameters, this has nothing to do with arrays – ᴄʀᴏᴢᴇᴛ Aug 14 '18 at 14:00

3 Answers3

3

The arguments that are inside [] are optional. The [, means that if you want to specify the arguments after that you must add the ,. In the use of the function, you don't have to write [].

Also you don't have to specify the type of each parameter, it's shown in the documentation to make you know what you have to pass.

Arguments that contain a = in the documentation are usually optional, and the value after the equal in the documentation means the default value.

altrisi
  • 131
  • 7
1

That is just how PHP documents optional arguments. You don't use brackets for those.

So you would only need to provide the $pattern and $subject and can optionally provide a reference array for $matches, an integer for $flags, and an integer for $offset.

If you don't provide the optional arguments, you wouldn't have a comma after $subject, hence why the comma is in the brackets.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • thank you for the answer, but why do they nested here, while in practice they used one by one? – ogbofjnr Aug 14 '18 at 13:03
  • My internet went out while I was adding more details. My edit should cover more. – Devon Bessemer Aug 14 '18 at 13:06
  • 1
    @MarkAmbrazhevich That makes each one optional. If it was `[, array &$matches, int $flags]` then using one would require the use of the second. However, I do not recall any functions which do this... – MonkeyZeus Aug 14 '18 at 13:06
1

Here, the square brackets have nothing to do with arrays, they mean that the parameters are optional.

More info about how to read a function definition in the PHP doc can be found here: http://php.net/manual/en/about.prototypes.php

Adrien
  • 26
  • 2