#fun with typecasts
fun with typecasts
!!$foo
will turn any truthy value totrue
(or1
in output), falsy values (0, empty string, empty array) tofalse
(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
orfoo^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 does not work: To multiply any number in a variable with
10
, you could append a zero:*10
->.0
. But in this case, PHP will take the dot as decimal point and complain. (It´s different though if you have a variable amount of zeroes in a string.)To turn an array into a string, use
join
instead ofimplode
.
If you don´t need a delimiter, don´t use it:join($a)
does the same asjoin('',$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
tobA
,A1
toA2
,A9
toB0
andz99Z
toaa00A
.
Decrement does not work on strings. (And it does not onNULL
).
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.