Notes on PHP

Subtle differences from other languages

  1. Ternary operator ?: is left-associative, unlike in C:

    • (TRUE ? 1 : TRUE ? 2 : 3) === 2

    • (TRUE ? 1 : (TRUE ? 2 : 3)) === 1

    • See: comment.

Subtle corner cases

  1. str_split with an empty string behaves like a special case (although the reasoning is documented).

    • str_split("") === array(""), not array().

    • Careful with foreach(str_split($string) as $char) { /* ... */ }

    • See: bug 37048.

Tricky types

  1. Arrays are always treated as associative, even if their keys are implicitly numeric.

    • array(5) + array(6) === array(5). Use array_merge instead. See comment.

  2. Strings are compared to strings numerically if possible (“smart” comparison). When comparing a string to a number this kind of conversion can be expected, but for two strings it's more surprising, and also different.

    • "+" < "-", but "+5" > "-5"

    • "+5" == "5" (see bug 43304), "1.2" == "1.20" (see bug 1974, bug 25763), "1" == "1e0" (see bug 23110)

    • "0xa" == "10" (see bug 39084)

    • " 5" == "5", but "5 " != "5"

    • "5z" != "5" (strict conversion), while "5z" == 5 (permissive conversion)

    • "1000000000000000000001"=="1000000000000000000002" (see bug 25943)

    • The documentation is misleading: === differs from == not only in comparing types, but also in not doing the numerical conversion (bug 50738 didn't say this). See bug 53908.

Security considerations

  1. mt_rand is initialized with one of at most just 232 seeds. This happens every time the interpreter is started (see PHP extensions, mt_rand is in the basic extension).

    • This means that if the first request the interpreter handles generates a cryptographic key, it will only generate one of 232 keys, no matter the bit length.

    • For CGI, a new interpreter is started for every request. For mod_php and FastCGI, each process is restarted after a certain number of requests, and new processes are started when many requests arrive simultaneously.

    • Use /dev/urandom for generating session cookies and short-term key material.