Skip to main content
2 of 4
removed string looping; tweaked other topics, added string increment.
Titus
  • 14.8k
  • 1
  • 24
  • 41

#fun with typecasts

  • !!$foo will turn any truthy value to true (or 1 in output), falsy values (0, empty string, empty array) to false (or empty output)
    This will rarely be needed in code golf, for in most cases where you need a boolean, there is an implicit cast anyway.

  • (int)$foo can be written as $foo|0 or foo^0, but may need parentheses.
    For booleans and strings, $foo*1 or +$foo can be used to cast to int.

  • Unlike most other languages, PHP handles strings with numeric values as numbers. So if you have any string that contains a number you have to calculate with, just calculate.

  • The other way works as well: To multiply any number in a variable with 10, you can append a zero: *10 -> .0 saves one byte and has almost the same precedence.
    This does not work on any parenthesized expressions, function calls included.

  • To turn an array into a string, use join instead of implode.
    If you don´t need a delimiter, don´t use it: join($a) does the same as join('',$a)

  • Incrementing strings: The most amazing feature imo is that $s=a;$s++; produces $s=b;. This works with uppercase and lowercase characters. $s=Z;$s++; results in $s=AA;.
    This also works with mixed case: aZ to bA, A1 to A2, A9 to B0 and z99Z to aa00A.
    Decrement does not work on strings. (And it does not on NULL).
    Back in PHP 3, $n="001";$n++; produced $n="002";. I am a little sad they removed that.

Whatever you golf: always have the operator precedence table at hand.

Titus
  • 14.8k
  • 1
  • 24
  • 41