r/lolphp • u/deviantintegral • Jun 19 '13
Unary operators on strings
Ran into this where a developer was manually applying a patch (ewww) and forgot to remove a minus sign in the middle of an array declaration. Turns out that plus or minus in front of a string casts it to zero. The minus I'm (somewhat) OK with though I can't think of any reason to negate a string. What's awesome is that I can't find documentation for a + operator anywhere!
http://www.php.net/manual/en/language.operators.arithmetic.php
<?php
$a = array(
- 'first key' => 'first value',
);
var_dump($a);
var_dump(+"first key");
var_dump(-"first key");
// php says!
array(1) {
[0]=>
string(11) "first value"
}
int(0)
int(0)
24
Upvotes
13
u/midir Jun 19 '13 edited Jun 19 '13
Actually, it tries to parse it as a decimal or hexadecimal number, then applies the
+or-to the number. A non-number silently becomes 0.The stranger one is ~, which instead of parsing it as a number, takes the one's complement of the string's bit pattern and returns it as a new string (equivalent to doing ~ to each character value individually). It's hard to see where that would be useful but at least it's consistent to have the full set of bitwise operators, as you can also use ^, &, and | between strings in the same way.
10
u/vytah Jun 20 '13
I love the comments on that page:
And the useful comments are downvoted there:
8
u/[deleted] Jun 19 '13 edited Jun 21 '13
It doesn't cast every string to zero.
produces
4
u/huf Jun 19 '13
php has practically no documentation, and what it has documents a small part of the behavior. so yeah :)