Skip to main content
1 of 4
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), and in most cases you can also drop the parentheses. $foo*1 or $foo+0 might be a better choice in some cases.

  • 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)

  • Walking through strings char by char is at least two bytes (up to 10 bytes) shorter with foreach(str_split($s)as$i=>$c){$c} instead of for($i=0;$i<strlen($s);$i++){$s[$i]}.

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

Titus
  • 14.8k
  • 1
  • 24
  • 41