subreddit stringclasses 7
values | author stringlengths 3 20 | id stringlengths 5 7 | content stringlengths 67 30.4k | score int64 0 140k |
|---|---|---|---|---|
lolphp | Banane9 | cms389p | <|sols|><|sot|>PHP :: Bug #53711 :: Casting float->string->float with locale<|eot|><|sol|>https://bugs.php.net/bug.php?id=53711<|eol|><|sor|>Heh "won't fix". Essentially because fixing it would be hard. <|eor|><|sor|>And the proposed solution: create an .ini setting.
Pure gold.<|eor|><|sor|>Even better that the .ini solution defaults to "stay_broken = true"
<|eor|><|sor|>Nono, it's "keep_backwards_compatibility_at_all_costs = true", duh
Edit: Add important last bit<|eor|><|eols|><|endoftext|> | 8 |
lolphp | stesch | cmspz4x | <|sols|><|sot|>PHP :: Bug #53711 :: Casting float->string->float with locale<|eot|><|sol|>https://bugs.php.net/bug.php?id=53711<|eol|><|sor|>For comparison:
keith@Keiths-Hackintosh ~ $ irb
2.0.0-p247 :001 > (1234.56.to_s).to_f == 1234.56
=> true
<|eor|><|sor|>Hm, what happens if you change the locale? <|eor|><|sor|>There's no global locale to be set. *Encoding*, sure, but that should almost always be UTF-8, and strings track their encoding (so converting a float to a string and then changing the global encoding doesn't affect the existing string).
If you want to output a number in a locale-specific way, you use a library which understands locales (like the I18n library, which is part of the standard library). There is literally no explanation for PHP's incorrect behavior other than bad design.<|eor|><|sor|>1234.56 is as much a locale-specific way of formatting a float as 1234,56 is. Locales don't just mean "non-US_English places".<|eor|><|soopr|>No, it's the "canonical string representation". Which coincidently is written with a point and no separator between groups of thousands.
If I would want to use a different formatting, I would call [number_format](http://php.net/manual/en/function.number-format.php) or [sprintf](http://php.net/manual/en/function.sprintf.php).
By the way: [floatval](http://php.net/manual/en/function.floatval.php) isn't locale aware. ;-)
<|eoopr|><|eols|><|endoftext|> | 8 |
lolphp | frezik | cmxwkk7 | <|sols|><|sot|>PHP :: Bug #53711 :: Casting float->string->float with locale<|eot|><|sol|>https://bugs.php.net/bug.php?id=53711<|eol|><|sor|>Heh "won't fix". Essentially because fixing it would be hard. <|eor|><|sor|>It's not because it'd be hard, it's because inevitably a lot of people rely on this and you'd break their code.<|eor|><|sor|>In other words, it's because it's hard.<|eor|><|eols|><|endoftext|> | 6 |
lolphp | allthediamonds | cms5z89 | <|sols|><|sot|>PHP :: Bug #53711 :: Casting float->string->float with locale<|eot|><|sol|>https://bugs.php.net/bug.php?id=53711<|eol|><|sor|>Please, PHP, just stop trying. Save yourself further embarrassment.<|eor|><|eols|><|endoftext|> | 5 |
lolphp | ZiggyTheHamster | cms684l | <|sols|><|sot|>PHP :: Bug #53711 :: Casting float->string->float with locale<|eot|><|sol|>https://bugs.php.net/bug.php?id=53711<|eol|><|sor|>For comparison:
keith@Keiths-Hackintosh ~ $ irb
2.0.0-p247 :001 > (1234.56.to_s).to_f == 1234.56
=> true
<|eor|><|eols|><|endoftext|> | 5 |
lolphp | ZiggyTheHamster | cms78k9 | <|sols|><|sot|>PHP :: Bug #53711 :: Casting float->string->float with locale<|eot|><|sol|>https://bugs.php.net/bug.php?id=53711<|eol|><|sor|>For comparison:
keith@Keiths-Hackintosh ~ $ irb
2.0.0-p247 :001 > (1234.56.to_s).to_f == 1234.56
=> true
<|eor|><|sor|>Hm, what happens if you change the locale? <|eor|><|sor|>There's no global locale to be set. *Encoding*, sure, but that should almost always be UTF-8, and strings track their encoding (so converting a float to a string and then changing the global encoding doesn't affect the existing string).
If you want to output a number in a locale-specific way, you use a library which understands locales (like the I18n library, which is part of the standard library). There is literally no explanation for PHP's incorrect behavior other than bad design.<|eor|><|eols|><|endoftext|> | 5 |
lolphp | jamieflournoy | cmtbc1s | <|sols|><|sot|>PHP :: Bug #53711 :: Casting float->string->float with locale<|eot|><|sol|>https://bugs.php.net/bug.php?id=53711<|eol|><|sor|>For comparison:
keith@Keiths-Hackintosh ~ $ irb
2.0.0-p247 :001 > (1234.56.to_s).to_f == 1234.56
=> true
<|eor|><|sor|>Hm, what happens if you change the locale? <|eor|><|sor|>There's no global locale to be set. *Encoding*, sure, but that should almost always be UTF-8, and strings track their encoding (so converting a float to a string and then changing the global encoding doesn't affect the existing string).
If you want to output a number in a locale-specific way, you use a library which understands locales (like the I18n library, which is part of the standard library). There is literally no explanation for PHP's incorrect behavior other than bad design.<|eor|><|sor|>1234.56 is as much a locale-specific way of formatting a float as 1234,56 is. Locales don't just mean "non-US_English places".<|eor|><|sor|>1234.56 is locale-neutral because _it's the native representation of a float_. Suppose the language used 1234f56 to represent a float... same thing, locale neutral. It just reads like shit. Your float type (or literally, any other type) should never care about locale - it's up to sprintf and friends to care. Otherwise, we end up in a situation where you would have to write `blah = falso` just because `LC_ALL=es_ES`, and that makes zero sense.
Say your programming language makes you use Asian decimal separators if the locale is set to an Asian locale, but English separators if the locale is set to an English locale. That makes no sense. It should always be one thing (which is English format in the majority of programming languages), and changed when outputting (by the language/runtime, not the programmer).<|eor|><|sor|>I think we misunderstood each other.
I realize now that OP's linked bug is probably talking about a use case involving serializing a float (a 64-bit IEEE value) as a string for use in a hidden field or URL or something, and then parsing that value right back into a float by the same program, without a user ever looking at the value.
In that case Ruby's Float.to_s and String.to_f work fine, while PHP's dumb (string) cast assumes that you always are printing for a user's consumption so why not localize it... based on a global variable taken from the execution environment, because this is PHP.
<|eor|><|eols|><|endoftext|> | 5 |
lolphp | immibis | 272twb | <|sols|><|sot|>In PHP, 0 + 2 is 2, but 0+2 is 4<|eot|><|sol|>https://bugs.php.net/bug.php?id=61095<|eol|><|eols|><|endoftext|> | 54 |
lolphp | poizan42 | chx26au | <|sols|><|sot|>In PHP, 0 + 2 is 2, but 0+2 is 4<|eot|><|sol|>https://bugs.php.net/bug.php?id=61095<|eol|><|sor|>Wow, a bug that got fixed a few years ago! Who would have thought that software has bugs?<|eor|><|sor|>If you had ever written a compiler you would know that a bug such as this would take some serious effort to get if you had anything that could be called a sane design. You would have a lexer which would always match '+' as a token (unless part of a comment or string). Considering that neither '+' nor whitespace can be a part of a number, the lexer would have to output the tokens "0x00", "+", "2" in both cases, and the parser wouldn't even be able to tell the difference.
But the "lexer" in php is... well.. kindof ad-hoc-ish spaghetti... Just look at [the actual fix](http://svn.php.net/viewvc/php/php-src/branches/PHP_5_3/Zend/zend_language_scanner.l?r1=323394&r2=323393&pathrev=323394).<|eor|><|eols|><|endoftext|> | 21 |
lolphp | dehrmann | chx0czy | <|sols|><|sot|>In PHP, 0 + 2 is 2, but 0+2 is 4<|eot|><|sol|>https://bugs.php.net/bug.php?id=61095<|eol|><|sor|>Pretty sure 90% of the class got this right in my compilers course.<|eor|><|eols|><|endoftext|> | 14 |
lolphp | callcifer | 1zk0y4 | <|sols|><|sot|>Wait, what? How is this possible even with weak comparison?<|eot|><|sol|>https://eval.in/111886<|eol|><|eols|><|endoftext|> | 53 |
lolphp | lisp-case | cfube6c | <|sols|><|sot|>Wait, what? How is this possible even with weak comparison?<|eot|><|sol|>https://eval.in/111886<|eol|><|sor|>It's tripping over the "numeric string" condition. Because for *some reason* PHP decided that when you compare two strings that look like numbers, they will both be converted to floats and then compared.
Those hashes have an exponential part: they begin `0e` and continue on to have only digits. ` n : nat. 0 * n = 0`, so in PHP `md5('240610708') == md5('QNKCDZO')`.
And yes, this is exactly as stupid as it looks.
Edit: numbers of the form *n*e*m* are *n* * 10^*m*, not *n*^*m*. What am I doing.<|eor|><|eols|><|endoftext|> | 38 |
lolphp | ThisIsADogHello | cfuqam3 | <|sols|><|sot|>Wait, what? How is this possible even with weak comparison?<|eot|><|sol|>https://eval.in/111886<|eol|><|sor|>I haven't written PHP in years (and hope I never have to again), but I believe the correct way of dealing with this is to use [strcmp](http://php.net/strcmp) instead of comparing strings with the == operator.<|eor|><|sor|>[Only if you're sure the things you're comparing are actually strings.](http://danuxx.blogspot.com/2013/03/unauthorized-access-bypassing-php-strcmp.html)
PHP is an absolute fucking minefield when it comes to writing secure software. There's so many ways to do everything, and almost all of them are subtly broken in some seriously dangerous way.<|eor|><|eols|><|endoftext|> | 22 |
lolphp | tdammers | cfuv1sp | <|sols|><|sot|>Wait, what? How is this possible even with weak comparison?<|eot|><|sol|>https://eval.in/111886<|eol|><|sor|>[deleted]<|eor|><|sor|>It's not reasonable; it's what the people who made it were capable of implementing. Then PHP accidentally became popular, and before anyone realized there was a problem, the behavior was cemented, and nobody had any clue how to "fix" it. Until someone came up with a genius solution: just declare and document that this behavior is "by design", and be done with it.<|eor|><|sor|>[Except they're promoting it as a feature, not a bug](http://php.net/manual/en/language.types.type-juggling.php).
edit: d'oh, I'm blind and can't read<|eor|><|sor|>You are excused. PHP is known to cause temporary blindness and illiteracy.<|eor|><|eols|><|endoftext|> | 20 |
lolphp | tdammers | cfud5io | <|sols|><|sot|>Wait, what? How is this possible even with weak comparison?<|eot|><|sol|>https://eval.in/111886<|eol|><|sor|>[deleted]<|eor|><|sor|>It's not reasonable; it's what the people who made it were capable of implementing. Then PHP accidentally became popular, and before anyone realized there was a problem, the behavior was cemented, and nobody had any clue how to "fix" it. Until someone came up with a genius solution: just declare and document that this behavior is "by design", and be done with it.<|eor|><|eols|><|endoftext|> | 17 |
lolphp | hervold | cfuh017 | <|sols|><|sot|>Wait, what? How is this possible even with weak comparison?<|eot|><|sol|>https://eval.in/111886<|eol|><|sor|>[deleted]<|eor|><|sor|>I believe they aren't discarded. They are treated as an exponent in scientific floating point representation.
> var_dump('2e1' == '20');
bool(true)
<|eor|><|sor|>right, but they're as good as discarded as 0eX is zero irrespective of X.<|eor|><|eols|><|endoftext|> | 14 |
lolphp | piciu | cfuu692 | <|sols|><|sot|>Wait, what? How is this possible even with weak comparison?<|eot|><|sol|>https://eval.in/111886<|eol|><|sor|>I haven't written PHP in years (and hope I never have to again), but I believe the correct way of dealing with this is to use [strcmp](http://php.net/strcmp) instead of comparing strings with the == operator.<|eor|><|sor|>Or use the === operator.<|eor|><|eols|><|endoftext|> | 11 |
lolphp | vytah | cfugtdh | <|sols|><|sot|>Wait, what? How is this possible even with weak comparison?<|eot|><|sol|>https://eval.in/111886<|eol|><|sor|>[deleted]<|eor|><|sor|>I believe they aren't discarded. They are treated as an exponent in scientific floating point representation.
> var_dump('2e1' == '20');
bool(true)
<|eor|><|eols|><|endoftext|> | 8 |
lolphp | MachaHack | cfx1fpi | <|sols|><|sot|>Wait, what? How is this possible even with weak comparison?<|eot|><|sol|>https://eval.in/111886<|eol|><|sor|>And now I realise that something I wrote when I was 14 had even worse security issues than using unsalted md5 for passwords. I'm glad that never got deployed anywhere useful.<|eor|><|eols|><|endoftext|> | 7 |
lolphp | Dereleased | 1fnt34 | <|soss|><|sot|>Weird properties of PHP's lexer and parser<|eot|><|sost|>There are (as of PHP 5.3.0) only two tokens which represent a single character:
* T_NAMESPACE_SEPARATOR: `\`
* T_CURLY_OPEN: `{`
* This only occurs inside of interpolated strings, e.g. "{$foo}" lexes to: `'"' T_CURLY_OPEN T_VARIABLE '}' '"'`
* ~~Technically, there is a third, T_BAD_CHARACTER, but it is non-specific.~~ No longer true according to one of the php devs
There are two items in the parser which, instead of being unspecified and generating a generic parse error, exist only to throw a special parse error:
* using `isset()` with something other than a variable
* using `__halt_compiler()` anywhere other than the global scope (e.g., inside a function, conditional or loop)
([Shameless blog plug on this one](http://www.dereleased.com/2013/01/29/adventures-in-parsing-phps-implicit-semicolon-before-every-close-tag/)) The closing tag `?>` is implicitly converted to a semicolon. The opening tag consumes one character of whitepace (or two in case of windows newlines) after the literal tag, but is otherwise completely ignored by the parser. Thus, the following code is syntactically correct:
for ( $i = 0 ?><?php $i < 10 ?><?php ++$i ) echo "$i\n" ?>
And it lexes (after the first round transform) to
T_FOR '(' T_VARIABLE '=' T_LNUMBER ';' T_VARIABLE '<' T_LNUMBER ';'
T_INC T_VARIABLE ')' T_ECHO '"' T_VARIABLE
T_ENCAPSED_AND_WHITESPACE '"' ';'
The next several relate to variable interpolation syntax. For these, it helps to know the difference between a statement (`if`, `for`, `while`, etc) and an expression (something with a value, like a variable, object lookup, function call, etc).
0. If you interpolate an array with a single element lookup and no braces, non-identifier-non-whitespace chars will be parsed as single-character tokens until either a whitespace character or closing bracket is encountered.
* e.g., "$foo["bar$$foo]" lexes to `'"' T_VARIABLE '[' '"' T_STRING '$' '$' T_STRING ']' '"'`
0. In a similar scenario to the above, if you do use a space inside the braces, you will get an extra, empty `T_ENCAPSED_AND_WHITESPACE` token.
* e.g., "$foo[ whatever here" lexes to `'"' T_VARIABLE '[' T_ENCAPSED_AND_WHITESPACE T_ENCAPSED_AND_WHITESPACE '"'`
0. In the midst of complex interpolation, if you are in one of the constructs that allows you to use full expressions, you can insert a closing tag (which PHP considers to be the same as a ';' and therefore bad syntax, but nevertheless), and it will be parsed as such. Furthermore, if you use an open tag, the lexer will remember that you were in the middle of an expression inside a string interpolation, although this seems like a moment of good design and implementation (or something like it).
You can nest heredocs. Seriously. Consider the following:
echo <<<THONE
${<<<THTWO
test
THTWO
}
THONE;
You can nest it as deep as you want, which is ~~terrible~~ (edit: a terrible thing to do), but what is hilarious is that, while the actual PHP interpreter handles this scenario correctly, the PHP userland tokenizer, [`token_get_all()`](http://php.net/token-get-all), cannot handle it, and parses the remainder of the source after the innermost heredoc to be one long interpolated string (edit: according to a person on the php dev team, this is fixed in 5.5).
I hope these oddities have been as amusing for you to read about here as they have been for me to discover.
<|eost|><|eoss|><|endoftext|> | 55 |
lolphp | olemartinorg | cac30fh | <|soss|><|sot|>Weird properties of PHP's lexer and parser<|eot|><|sost|>There are (as of PHP 5.3.0) only two tokens which represent a single character:
* T_NAMESPACE_SEPARATOR: `\`
* T_CURLY_OPEN: `{`
* This only occurs inside of interpolated strings, e.g. "{$foo}" lexes to: `'"' T_CURLY_OPEN T_VARIABLE '}' '"'`
* ~~Technically, there is a third, T_BAD_CHARACTER, but it is non-specific.~~ No longer true according to one of the php devs
There are two items in the parser which, instead of being unspecified and generating a generic parse error, exist only to throw a special parse error:
* using `isset()` with something other than a variable
* using `__halt_compiler()` anywhere other than the global scope (e.g., inside a function, conditional or loop)
([Shameless blog plug on this one](http://www.dereleased.com/2013/01/29/adventures-in-parsing-phps-implicit-semicolon-before-every-close-tag/)) The closing tag `?>` is implicitly converted to a semicolon. The opening tag consumes one character of whitepace (or two in case of windows newlines) after the literal tag, but is otherwise completely ignored by the parser. Thus, the following code is syntactically correct:
for ( $i = 0 ?><?php $i < 10 ?><?php ++$i ) echo "$i\n" ?>
And it lexes (after the first round transform) to
T_FOR '(' T_VARIABLE '=' T_LNUMBER ';' T_VARIABLE '<' T_LNUMBER ';'
T_INC T_VARIABLE ')' T_ECHO '"' T_VARIABLE
T_ENCAPSED_AND_WHITESPACE '"' ';'
The next several relate to variable interpolation syntax. For these, it helps to know the difference between a statement (`if`, `for`, `while`, etc) and an expression (something with a value, like a variable, object lookup, function call, etc).
0. If you interpolate an array with a single element lookup and no braces, non-identifier-non-whitespace chars will be parsed as single-character tokens until either a whitespace character or closing bracket is encountered.
* e.g., "$foo["bar$$foo]" lexes to `'"' T_VARIABLE '[' '"' T_STRING '$' '$' T_STRING ']' '"'`
0. In a similar scenario to the above, if you do use a space inside the braces, you will get an extra, empty `T_ENCAPSED_AND_WHITESPACE` token.
* e.g., "$foo[ whatever here" lexes to `'"' T_VARIABLE '[' T_ENCAPSED_AND_WHITESPACE T_ENCAPSED_AND_WHITESPACE '"'`
0. In the midst of complex interpolation, if you are in one of the constructs that allows you to use full expressions, you can insert a closing tag (which PHP considers to be the same as a ';' and therefore bad syntax, but nevertheless), and it will be parsed as such. Furthermore, if you use an open tag, the lexer will remember that you were in the middle of an expression inside a string interpolation, although this seems like a moment of good design and implementation (or something like it).
You can nest heredocs. Seriously. Consider the following:
echo <<<THONE
${<<<THTWO
test
THTWO
}
THONE;
You can nest it as deep as you want, which is ~~terrible~~ (edit: a terrible thing to do), but what is hilarious is that, while the actual PHP interpreter handles this scenario correctly, the PHP userland tokenizer, [`token_get_all()`](http://php.net/token-get-all), cannot handle it, and parses the remainder of the source after the innermost heredoc to be one long interpolated string (edit: according to a person on the php dev team, this is fixed in 5.5).
I hope these oddities have been as amusing for you to read about here as they have been for me to discover.
<|eost|><|sor|>Nice! I'm contemplating putting that for loop in a central part of our codebase so that the next person who stumbles over it gets a real good WTF moment.. :-) <|eor|><|eoss|><|endoftext|> | 12 |
lolphp | Dereleased | cac29u2 | <|soss|><|sot|>Weird properties of PHP's lexer and parser<|eot|><|sost|>There are (as of PHP 5.3.0) only two tokens which represent a single character:
* T_NAMESPACE_SEPARATOR: `\`
* T_CURLY_OPEN: `{`
* This only occurs inside of interpolated strings, e.g. "{$foo}" lexes to: `'"' T_CURLY_OPEN T_VARIABLE '}' '"'`
* ~~Technically, there is a third, T_BAD_CHARACTER, but it is non-specific.~~ No longer true according to one of the php devs
There are two items in the parser which, instead of being unspecified and generating a generic parse error, exist only to throw a special parse error:
* using `isset()` with something other than a variable
* using `__halt_compiler()` anywhere other than the global scope (e.g., inside a function, conditional or loop)
([Shameless blog plug on this one](http://www.dereleased.com/2013/01/29/adventures-in-parsing-phps-implicit-semicolon-before-every-close-tag/)) The closing tag `?>` is implicitly converted to a semicolon. The opening tag consumes one character of whitepace (or two in case of windows newlines) after the literal tag, but is otherwise completely ignored by the parser. Thus, the following code is syntactically correct:
for ( $i = 0 ?><?php $i < 10 ?><?php ++$i ) echo "$i\n" ?>
And it lexes (after the first round transform) to
T_FOR '(' T_VARIABLE '=' T_LNUMBER ';' T_VARIABLE '<' T_LNUMBER ';'
T_INC T_VARIABLE ')' T_ECHO '"' T_VARIABLE
T_ENCAPSED_AND_WHITESPACE '"' ';'
The next several relate to variable interpolation syntax. For these, it helps to know the difference between a statement (`if`, `for`, `while`, etc) and an expression (something with a value, like a variable, object lookup, function call, etc).
0. If you interpolate an array with a single element lookup and no braces, non-identifier-non-whitespace chars will be parsed as single-character tokens until either a whitespace character or closing bracket is encountered.
* e.g., "$foo["bar$$foo]" lexes to `'"' T_VARIABLE '[' '"' T_STRING '$' '$' T_STRING ']' '"'`
0. In a similar scenario to the above, if you do use a space inside the braces, you will get an extra, empty `T_ENCAPSED_AND_WHITESPACE` token.
* e.g., "$foo[ whatever here" lexes to `'"' T_VARIABLE '[' T_ENCAPSED_AND_WHITESPACE T_ENCAPSED_AND_WHITESPACE '"'`
0. In the midst of complex interpolation, if you are in one of the constructs that allows you to use full expressions, you can insert a closing tag (which PHP considers to be the same as a ';' and therefore bad syntax, but nevertheless), and it will be parsed as such. Furthermore, if you use an open tag, the lexer will remember that you were in the middle of an expression inside a string interpolation, although this seems like a moment of good design and implementation (or something like it).
You can nest heredocs. Seriously. Consider the following:
echo <<<THONE
${<<<THTWO
test
THTWO
}
THONE;
You can nest it as deep as you want, which is ~~terrible~~ (edit: a terrible thing to do), but what is hilarious is that, while the actual PHP interpreter handles this scenario correctly, the PHP userland tokenizer, [`token_get_all()`](http://php.net/token-get-all), cannot handle it, and parses the remainder of the source after the innermost heredoc to be one long interpolated string (edit: according to a person on the php dev team, this is fixed in 5.5).
I hope these oddities have been as amusing for you to read about here as they have been for me to discover.
<|eost|><|sor|>I don't really get the purpose of heredocs to begin with, why would I use that instead of a string?<|eor|><|soopr|>If you wanted to have a string that included a lot of quotes (JSON, XML, or HTML for example) without having to constantly escape them.<|eoopr|><|eoss|><|endoftext|> | 11 |
lolphp | dipswitch | cac3j67 | <|soss|><|sot|>Weird properties of PHP's lexer and parser<|eot|><|sost|>There are (as of PHP 5.3.0) only two tokens which represent a single character:
* T_NAMESPACE_SEPARATOR: `\`
* T_CURLY_OPEN: `{`
* This only occurs inside of interpolated strings, e.g. "{$foo}" lexes to: `'"' T_CURLY_OPEN T_VARIABLE '}' '"'`
* ~~Technically, there is a third, T_BAD_CHARACTER, but it is non-specific.~~ No longer true according to one of the php devs
There are two items in the parser which, instead of being unspecified and generating a generic parse error, exist only to throw a special parse error:
* using `isset()` with something other than a variable
* using `__halt_compiler()` anywhere other than the global scope (e.g., inside a function, conditional or loop)
([Shameless blog plug on this one](http://www.dereleased.com/2013/01/29/adventures-in-parsing-phps-implicit-semicolon-before-every-close-tag/)) The closing tag `?>` is implicitly converted to a semicolon. The opening tag consumes one character of whitepace (or two in case of windows newlines) after the literal tag, but is otherwise completely ignored by the parser. Thus, the following code is syntactically correct:
for ( $i = 0 ?><?php $i < 10 ?><?php ++$i ) echo "$i\n" ?>
And it lexes (after the first round transform) to
T_FOR '(' T_VARIABLE '=' T_LNUMBER ';' T_VARIABLE '<' T_LNUMBER ';'
T_INC T_VARIABLE ')' T_ECHO '"' T_VARIABLE
T_ENCAPSED_AND_WHITESPACE '"' ';'
The next several relate to variable interpolation syntax. For these, it helps to know the difference between a statement (`if`, `for`, `while`, etc) and an expression (something with a value, like a variable, object lookup, function call, etc).
0. If you interpolate an array with a single element lookup and no braces, non-identifier-non-whitespace chars will be parsed as single-character tokens until either a whitespace character or closing bracket is encountered.
* e.g., "$foo["bar$$foo]" lexes to `'"' T_VARIABLE '[' '"' T_STRING '$' '$' T_STRING ']' '"'`
0. In a similar scenario to the above, if you do use a space inside the braces, you will get an extra, empty `T_ENCAPSED_AND_WHITESPACE` token.
* e.g., "$foo[ whatever here" lexes to `'"' T_VARIABLE '[' T_ENCAPSED_AND_WHITESPACE T_ENCAPSED_AND_WHITESPACE '"'`
0. In the midst of complex interpolation, if you are in one of the constructs that allows you to use full expressions, you can insert a closing tag (which PHP considers to be the same as a ';' and therefore bad syntax, but nevertheless), and it will be parsed as such. Furthermore, if you use an open tag, the lexer will remember that you were in the middle of an expression inside a string interpolation, although this seems like a moment of good design and implementation (or something like it).
You can nest heredocs. Seriously. Consider the following:
echo <<<THONE
${<<<THTWO
test
THTWO
}
THONE;
You can nest it as deep as you want, which is ~~terrible~~ (edit: a terrible thing to do), but what is hilarious is that, while the actual PHP interpreter handles this scenario correctly, the PHP userland tokenizer, [`token_get_all()`](http://php.net/token-get-all), cannot handle it, and parses the remainder of the source after the innermost heredoc to be one long interpolated string (edit: according to a person on the php dev team, this is fixed in 5.5).
I hope these oddities have been as amusing for you to read about here as they have been for me to discover.
<|eost|><|sor|>I don't really get the purpose of heredocs to begin with, why would I use that instead of a string?<|eor|><|soopr|>If you wanted to have a string that included a lot of quotes (JSON, XML, or HTML for example) without having to constantly escape them.<|eoopr|><|sor|>Or to get the proper syntax highlighting.<|eor|><|eoss|><|endoftext|> | 8 |
lolphp | MilkshakeYeah | 1eieco | <|soss|><|sot|>is_a function change of heart<|eot|><|sost|>5.0.0 This function became deprecated in favour of the instanceof operator. Calling this function will result in an E_STRICT warning.
5.3.0 This function is no longer deprecated, and will therefore no longer throw E_STRICT warnings.
http://pl1.php.net/manual/en/function.is-a.php<|eost|><|eoss|><|endoftext|> | 52 |
lolphp | emarocca | 11im47 | <|sols|><|sot|>intval returns the integer value of var on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1. Very big values return 0. Strings will most likely return 0. Sometimes 1.<|eot|><|sol|>http://php.net/manual/en/function.intval.php<|eol|><|eols|><|endoftext|> | 53 |
lolphp | chellomere | c6mw2bh | <|sols|><|sot|>intval returns the integer value of var on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1. Very big values return 0. Strings will most likely return 0. Sometimes 1.<|eot|><|sol|>http://php.net/manual/en/function.intval.php<|eol|><|sor|>Down in the comments you find this genius:
inval work well with numbers except the kind:
intval("10.2e+2")
which gives 10
the trick around is to use the following function:
<?php
function smart_val($string) {
eval("\$number=$string;");
return $number;
}
?>
Doing <?php echo smart_val("10.2e+2"); ?>
gives: 1020
Edit: apparently you don't need to escape backslash in code on reddit<|eor|><|eols|><|endoftext|> | 14 |
lolphp | Rhomboid | c6mzya7 | <|sols|><|sot|>intval returns the integer value of var on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1. Very big values return 0. Strings will most likely return 0. Sometimes 1.<|eot|><|sol|>http://php.net/manual/en/function.intval.php<|eol|><|sor|>BUT WAIT THERE IS MORE
For some reason I scroll down and look at the comment horror show, and I see this oddity:
Idsky 09-Aug-2012 08:03
Wow, floating point issues are worse that I expected!
<?php
echo intval((1.2-1)*10); // outputs 1, rather than 2 like you might expect.
?>
I'm like "no fucking way that could fail".
headless ~ # php -v; php test.php
PHP 5.4.7--pl0-gentoo (cli) (built: Sep 18 2012 18:36:20)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
1
headless ~ #
LOL php can't do floating point math.<|eor|><|sor|>Uh, I'm pretty sure that's expected behavior. I get the same thing in Haskell and Python.<|eor|><|sor|>So in Haskell and Python, the integer value of 2 is 1?
<|eor|><|sor|>No, Haskell and Python use floating point math by default, and floating point arithmetic cannot represent .2 exactly; the closest representation is slightly less than .2, so when you multiply it by 10 and then round down you get 1. Most languages do this because exact decimal arithmetic is *really slow*.<|eor|><|sor|>I know this, however I stand by my assertion that PHP still can't do floating point math because the answer is 2 because that is what PHP is returning. Not 2 minus epsilon, but 2 exactly because this is one of those things that can be done exactly.
Though I have no idea if PHP is smart enough to realize there are operations that can be done without invoking floating point math...
headless ~ # cat test.php
<?php
$test=(1.2-1)*10;
print_r($test-2);
?>
headless ~ # php test.php
-4.4408920985006E-16
In this case, since zero rounding is done, this is mathematically equivalent to floor. Does php have floor?
http://php.net/manual/en/function.floor.php
headless ~ # cat test.php; php test.php
<?php
$test=(1.2-1)*10;
print_r(floor($test-2));
?>
-1
WHAT THE FUCK
Floating point error gives a slightly negative value which means intval doesn't work like you'd expect, and floor then works exactly as intended on the floating point error.
This isn't a problem with the function its' a problem with how PHP handles floating point math!
<|eor|><|sor|>> but 2 exactly because this is one of those things that can be done exactly.
No, it most certainly cannot. Neither 1.2 nor 0.2 can be exactly represented in IEEE floating point. PHP in this case is not doing anything wrong, it's your notion of how floating point works that is flawed.
<|eor|><|eols|><|endoftext|> | 10 |
lolphp | Porges | c6n4mtl | <|sols|><|sot|>intval returns the integer value of var on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1. Very big values return 0. Strings will most likely return 0. Sometimes 1.<|eot|><|sol|>http://php.net/manual/en/function.intval.php<|eol|><|sor|> The integer value of var on success, or 0 on failure.
But
intval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1.
E_HAHAHAYOUARESCREWED<|eor|><|eols|><|endoftext|> | 9 |
lolphp | vytah | c6n51cb | <|sols|><|sot|>intval returns the integer value of var on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1. Very big values return 0. Strings will most likely return 0. Sometimes 1.<|eot|><|sol|>http://php.net/manual/en/function.intval.php<|eol|><|sor|> The integer value of var on success, or 0 on failure.
But
intval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1.
E_HAHAHAYOUARESCREWED<|eor|><|sor|>I think 1 means here a success in generating an error.<|eor|><|eols|><|endoftext|> | 7 |
lolphp | vytah | c6n4rg6 | <|sols|><|sot|>intval returns the integer value of var on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1. Very big values return 0. Strings will most likely return 0. Sometimes 1.<|eot|><|sol|>http://php.net/manual/en/function.intval.php<|eol|><|sor|>Jesus, these examples are ridiculous.
echo intval(420000000000000000000); // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8); // 42
echo intval('42', 8); // 34
echo intval(array()); // 0
echo intval(array('foo', 'bar')); // 1
I just look at this and shake my head.<|eor|><|sor|>The third and fourth one actually make some sense.
The rest doesn't.<|eor|><|sor|>Nope, because the int value of an array should be NaN, not a number.
Why? Because it's not a number!!!<|eor|><|sor|>I'm almost sure you've already seen this: https://www.destroyallsoftware.com/talks/wat
He should make a second talk, this time focused solely on PHP.<|eor|><|eols|><|endoftext|> | 7 |
lolphp | scshunt | c6mugrv | <|sols|><|sot|>intval returns the integer value of var on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1. Very big values return 0. Strings will most likely return 0. Sometimes 1.<|eot|><|sol|>http://php.net/manual/en/function.intval.php<|eol|><|sor|>But using it on an object is an error.<|eor|><|eols|><|endoftext|> | 5 |
lolphp | Rhomboid | c6mzvlf | <|sols|><|sot|>intval returns the integer value of var on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1. Very big values return 0. Strings will most likely return 0. Sometimes 1.<|eot|><|sol|>http://php.net/manual/en/function.intval.php<|eol|><|sor|>Down in the comments you find this genius:
inval work well with numbers except the kind:
intval("10.2e+2")
which gives 10
the trick around is to use the following function:
<?php
function smart_val($string) {
eval("\$number=$string;");
return $number;
}
?>
Doing <?php echo smart_val("10.2e+2"); ?>
gives: 1020
Edit: apparently you don't need to escape backslash in code on reddit<|eor|><|sor|>I'm ... speechless. The stupid, it burns.
I figured I'd have a look at the comments for [`floatval()`](http://php.net/manual/en/function.floatval.php) to see what they had to say. Spoiler alert: they're horrible. If you ever wanted a master class on how not to format things, read those comments.
<|eor|><|eols|><|endoftext|> | 5 |
lolphp | ilikeboyswithglasses | 5jjvuc | <|soss|><|sot|>assertEquals(x, y) always passes if x and y are MongoDB ObjectIDs<|eot|><|sost|>The following is a successfully passing PHPUnit test (PHP 7.0.9, PHPUnit 5.7.4):
use MongoDB\BSON\ObjectID;
class ObjectIDGenerationTest extends \PHPUnit_Framework_TestCase {
function testObjectIDComparison() {
$a = new ObjectID("585a80ffc01a5c89194c839c");
$b = new ObjectID("585a810dc6586dab1cf1f92e");
self::assertNotEquals(strval($a), strval($b));
self::assertFalse($a == $b);
self::assertEquals($a, $b); // WTF
}
}<|eost|><|eoss|><|endoftext|> | 54 |
lolphp | duskwuff | dbh0xcj | <|soss|><|sot|>assertEquals(x, y) always passes if x and y are MongoDB ObjectIDs<|eot|><|sost|>The following is a successfully passing PHPUnit test (PHP 7.0.9, PHPUnit 5.7.4):
use MongoDB\BSON\ObjectID;
class ObjectIDGenerationTest extends \PHPUnit_Framework_TestCase {
function testObjectIDComparison() {
$a = new ObjectID("585a80ffc01a5c89194c839c");
$b = new ObjectID("585a810dc6586dab1cf1f92e");
self::assertNotEquals(strval($a), strval($b));
self::assertFalse($a == $b);
self::assertEquals($a, $b); // WTF
}
}<|eost|><|sor|>Not sure whether to blame MongoDB or PHPUnit here, but it's certainly not PHP's fault.<|eor|><|eoss|><|endoftext|> | 28 |
lolphp | sloat | dbha42o | <|soss|><|sot|>assertEquals(x, y) always passes if x and y are MongoDB ObjectIDs<|eot|><|sost|>The following is a successfully passing PHPUnit test (PHP 7.0.9, PHPUnit 5.7.4):
use MongoDB\BSON\ObjectID;
class ObjectIDGenerationTest extends \PHPUnit_Framework_TestCase {
function testObjectIDComparison() {
$a = new ObjectID("585a80ffc01a5c89194c839c");
$b = new ObjectID("585a810dc6586dab1cf1f92e");
self::assertNotEquals(strval($a), strval($b));
self::assertFalse($a == $b);
self::assertEquals($a, $b); // WTF
}
}<|eost|><|sor|>Just guessing, but it may be converting the ObjectID to a string, then when doing the comparison, sees that it starts with a number, converts the string to a number which dumps the characters after "585".
Try it with two very different strings and see if it still happens.<|eor|><|eoss|><|endoftext|> | 22 |
lolphp | thenickdude | dbjasae | <|soss|><|sot|>assertEquals(x, y) always passes if x and y are MongoDB ObjectIDs<|eot|><|sost|>The following is a successfully passing PHPUnit test (PHP 7.0.9, PHPUnit 5.7.4):
use MongoDB\BSON\ObjectID;
class ObjectIDGenerationTest extends \PHPUnit_Framework_TestCase {
function testObjectIDComparison() {
$a = new ObjectID("585a80ffc01a5c89194c839c");
$b = new ObjectID("585a810dc6586dab1cf1f92e");
self::assertNotEquals(strval($a), strval($b));
self::assertFalse($a == $b);
self::assertEquals($a, $b); // WTF
}
}<|eost|><|sor|>Just guessing, but it may be converting the ObjectID to a string, then when doing the comparison, sees that it starts with a number, converts the string to a number which dumps the characters after "585".
Try it with two very different strings and see if it still happens.<|eor|><|sor|>Almost certainly the right answer. It's a well-known quirk of PHP that `"123foo" == "123bar"` evaluates to `true`. Somewhere in the guts of assertEquals someone is doing a comparison that is too loose (and disagreeing with the result of `==` for ObjectID's which is especially WTF).<|eor|><|sor|>> It's a well-known quirk of PHP that "123foo" == "123bar" evaluates to true.
lol, no it doesn't, that'd be insane:
php > echo "123foo" == "123bar" ? "true" : "false";
false
What does happen is this:
php > echo 123 == "123bar" ? "true" : "false";
true<|eor|><|eoss|><|endoftext|> | 14 |
lolphp | SirClueless | dbhq4j1 | <|soss|><|sot|>assertEquals(x, y) always passes if x and y are MongoDB ObjectIDs<|eot|><|sost|>The following is a successfully passing PHPUnit test (PHP 7.0.9, PHPUnit 5.7.4):
use MongoDB\BSON\ObjectID;
class ObjectIDGenerationTest extends \PHPUnit_Framework_TestCase {
function testObjectIDComparison() {
$a = new ObjectID("585a80ffc01a5c89194c839c");
$b = new ObjectID("585a810dc6586dab1cf1f92e");
self::assertNotEquals(strval($a), strval($b));
self::assertFalse($a == $b);
self::assertEquals($a, $b); // WTF
}
}<|eost|><|sor|>In php, objects are compared against their properties, not instance id.<|eor|><|sor|>But the two ObjectIDs seem to have different properties since they were given different parameters in the constructor<|eor|><|sor|>If they were user-created classes, you'd be right.
But as they're extension/internal (written in C) classes, all the real object data is probably not stored in properties. Most likely there's no properties at all. In that case, the `==` implementation cannot see that data and therefore can't compare it.
So perhaps what happened here is MongoDB hasn't overriden the `==` implementation, so PHP compared properties (none, so they're the same) and class (the same), and found the two objects to be the same. And, well, it's not strictly wrong, I guess.
Mind you, I haven't tested this hypothesis.<|eor|><|sor|>There's a counter-example to this hypothesis in the post already:
> self::assertFalse($a == $b);
So the objects compare false. Something else is going on with PHPUnit specifically.<|eor|><|eoss|><|endoftext|> | 14 |
lolphp | SirClueless | dbhq8wj | <|soss|><|sot|>assertEquals(x, y) always passes if x and y are MongoDB ObjectIDs<|eot|><|sost|>The following is a successfully passing PHPUnit test (PHP 7.0.9, PHPUnit 5.7.4):
use MongoDB\BSON\ObjectID;
class ObjectIDGenerationTest extends \PHPUnit_Framework_TestCase {
function testObjectIDComparison() {
$a = new ObjectID("585a80ffc01a5c89194c839c");
$b = new ObjectID("585a810dc6586dab1cf1f92e");
self::assertNotEquals(strval($a), strval($b));
self::assertFalse($a == $b);
self::assertEquals($a, $b); // WTF
}
}<|eost|><|sor|>Just guessing, but it may be converting the ObjectID to a string, then when doing the comparison, sees that it starts with a number, converts the string to a number which dumps the characters after "585".
Try it with two very different strings and see if it still happens.<|eor|><|sor|>Almost certainly the right answer. It's a well-known quirk of PHP that `"123foo" == "123bar"` evaluates to `true`. Somewhere in the guts of assertEquals someone is doing a comparison that is too loose (and disagreeing with the result of `==` for ObjectID's which is especially WTF).<|eor|><|eoss|><|endoftext|> | 11 |
lolphp | Plorkyeran | dbon4yi | <|soss|><|sot|>assertEquals(x, y) always passes if x and y are MongoDB ObjectIDs<|eot|><|sost|>The following is a successfully passing PHPUnit test (PHP 7.0.9, PHPUnit 5.7.4):
use MongoDB\BSON\ObjectID;
class ObjectIDGenerationTest extends \PHPUnit_Framework_TestCase {
function testObjectIDComparison() {
$a = new ObjectID("585a80ffc01a5c89194c839c");
$b = new ObjectID("585a810dc6586dab1cf1f92e");
self::assertNotEquals(strval($a), strval($b));
self::assertFalse($a == $b);
self::assertEquals($a, $b); // WTF
}
}<|eost|><|sor|>Just guessing, but it may be converting the ObjectID to a string, then when doing the comparison, sees that it starts with a number, converts the string to a number which dumps the characters after "585".
Try it with two very different strings and see if it still happens.<|eor|><|sor|>Almost certainly the right answer. It's a well-known quirk of PHP that `"123foo" == "123bar"` evaluates to `true`. Somewhere in the guts of assertEquals someone is doing a comparison that is too loose (and disagreeing with the result of `==` for ObjectID's which is especially WTF).<|eor|><|sor|>> It's a well-known quirk of PHP that "123foo" == "123bar" evaluates to true.
lol, no it doesn't, that'd be insane:
php > echo "123foo" == "123bar" ? "true" : "false";
false
What does happen is this:
php > echo 123 == "123bar" ? "true" : "false";
true<|eor|><|sor|>He may have been thinking of the similar `echo "0e462097431906509019562988736854" == "0e830400451993494058024219903391" ? "true" : "false";` where using `==` on two strings does not compare them as strings.<|eor|><|eoss|><|endoftext|> | 11 |
lolphp | the_alias_of_andrea | dbhfc3r | <|soss|><|sot|>assertEquals(x, y) always passes if x and y are MongoDB ObjectIDs<|eot|><|sost|>The following is a successfully passing PHPUnit test (PHP 7.0.9, PHPUnit 5.7.4):
use MongoDB\BSON\ObjectID;
class ObjectIDGenerationTest extends \PHPUnit_Framework_TestCase {
function testObjectIDComparison() {
$a = new ObjectID("585a80ffc01a5c89194c839c");
$b = new ObjectID("585a810dc6586dab1cf1f92e");
self::assertNotEquals(strval($a), strval($b));
self::assertFalse($a == $b);
self::assertEquals($a, $b); // WTF
}
}<|eost|><|sor|>In php, objects are compared against their properties, not instance id.<|eor|><|sor|>But the two ObjectIDs seem to have different properties since they were given different parameters in the constructor<|eor|><|sor|>If they were user-created classes, you'd be right.
But as they're extension/internal (written in C) classes, all the real object data is probably not stored in properties. Most likely there's no properties at all. In that case, the `==` implementation cannot see that data and therefore can't compare it.
So perhaps what happened here is MongoDB hasn't overriden the `==` implementation, so PHP compared properties (none, so they're the same) and class (the same), and found the two objects to be the same. And, well, it's not strictly wrong, I guess.
Mind you, I haven't tested this hypothesis.<|eor|><|eoss|><|endoftext|> | 8 |
lolphp | edave64 | dbhx92w | <|soss|><|sot|>assertEquals(x, y) always passes if x and y are MongoDB ObjectIDs<|eot|><|sost|>The following is a successfully passing PHPUnit test (PHP 7.0.9, PHPUnit 5.7.4):
use MongoDB\BSON\ObjectID;
class ObjectIDGenerationTest extends \PHPUnit_Framework_TestCase {
function testObjectIDComparison() {
$a = new ObjectID("585a80ffc01a5c89194c839c");
$b = new ObjectID("585a810dc6586dab1cf1f92e");
self::assertNotEquals(strval($a), strval($b));
self::assertFalse($a == $b);
self::assertEquals($a, $b); // WTF
}
}<|eost|><|sor|>In php, objects are compared against their properties, not instance id.<|eor|><|sor|>But the two ObjectIDs seem to have different properties since they were given different parameters in the constructor<|eor|><|sor|>If they were user-created classes, you'd be right.
But as they're extension/internal (written in C) classes, all the real object data is probably not stored in properties. Most likely there's no properties at all. In that case, the `==` implementation cannot see that data and therefore can't compare it.
So perhaps what happened here is MongoDB hasn't overriden the `==` implementation, so PHP compared properties (none, so they're the same) and class (the same), and found the two objects to be the same. And, well, it's not strictly wrong, I guess.
Mind you, I haven't tested this hypothesis.<|eor|><|sor|>Just looked at the PHP unit code. It does compare using ===. If that fails, it uses a custom comparator library, which has an object comparator, which deep copies the objects into associative arrays, then deep compares those. == Is not used.<|eor|><|eoss|><|endoftext|> | 8 |
lolphp | theinvsblman | 3mg5kx | <|soss|><|sot|>PHP's stat can actually be very expensive<|eot|><|sost|>Calling stat() on a path that contains many dots and double dots makes PHP perform an enormous amount of syscalls. Here's an [example PHP program](http://pastebin.com/KLPXb8jk) and its [strace output](https://gist.github.com/enneract/6a337c57dab6e8a4ba90). For comparison, the [equivalent C program](http://pastebin.com/9xNCZyR5) needs about 3 orders of magnitude less time to complete and [stats the path only once](http://pastebin.com/KsaJm6ew).
Could someone explain WTF is going on?
EDIT: I'm running PHP 5.6.13 (cli) on Linux x86_64.<|eost|><|eoss|><|endoftext|> | 56 |
lolphp | bart2019 | cveotaw | <|soss|><|sot|>PHP's stat can actually be very expensive<|eot|><|sost|>Calling stat() on a path that contains many dots and double dots makes PHP perform an enormous amount of syscalls. Here's an [example PHP program](http://pastebin.com/KLPXb8jk) and its [strace output](https://gist.github.com/enneract/6a337c57dab6e8a4ba90). For comparison, the [equivalent C program](http://pastebin.com/9xNCZyR5) needs about 3 orders of magnitude less time to complete and [stats the path only once](http://pastebin.com/KsaJm6ew).
Could someone explain WTF is going on?
EDIT: I'm running PHP 5.6.13 (cli) on Linux x86_64.<|eost|><|sor|>So, this is doing 3077-356 = 2721 `lstat` calls for a path with 3\*450 = 1350 parts, or 2 per path part plus 1?!? Jeezes.<|eor|><|eoss|><|endoftext|> | 26 |
lolphp | theinvsblman | cveptme | <|soss|><|sot|>PHP's stat can actually be very expensive<|eot|><|sost|>Calling stat() on a path that contains many dots and double dots makes PHP perform an enormous amount of syscalls. Here's an [example PHP program](http://pastebin.com/KLPXb8jk) and its [strace output](https://gist.github.com/enneract/6a337c57dab6e8a4ba90). For comparison, the [equivalent C program](http://pastebin.com/9xNCZyR5) needs about 3 orders of magnitude less time to complete and [stats the path only once](http://pastebin.com/KsaJm6ew).
Could someone explain WTF is going on?
EDIT: I'm running PHP 5.6.13 (cli) on Linux x86_64.<|eost|><|sor|>[deleted]<|eor|><|soopr|>The following code
stat("/tmp/test/foo/bar");
results in [57 syscalls](http://pastebin.com/tVU2mMnH), most of which are duplicates. The realpath cache is always empty too (probably because I'm using the PHP CLI).<|eoopr|><|eoss|><|endoftext|> | 21 |
lolphp | bart2019 | cvhy08d | <|soss|><|sot|>PHP's stat can actually be very expensive<|eot|><|sost|>Calling stat() on a path that contains many dots and double dots makes PHP perform an enormous amount of syscalls. Here's an [example PHP program](http://pastebin.com/KLPXb8jk) and its [strace output](https://gist.github.com/enneract/6a337c57dab6e8a4ba90). For comparison, the [equivalent C program](http://pastebin.com/9xNCZyR5) needs about 3 orders of magnitude less time to complete and [stats the path only once](http://pastebin.com/KsaJm6ew).
Could someone explain WTF is going on?
EDIT: I'm running PHP 5.6.13 (cli) on Linux x86_64.<|eost|><|sor|>> PHP resolves every paths it meets and splits every path part, resolving it. I explain : if you access the file "/home/julien/www/fooproject/app/web/entry.php", PHP is gonna split this path into as many single units as can fit. PHP is gonna resolve "/home", creating an entry for it into the cache. Then "/home/julien", then "/home/julien/www", etc.. Why this ? Well, first this is used to check access at every level of directory. Secondly, because many PHP users tend to build their pathnames using string concatenations, PHP may have a chance to have checked simple parts, it will then know if the user may access it or not, by asking the realpath cache for details. A cache hit is very cheap. The source code of tsrm_realpath_r() details the procedure. this is a recursive function which gets called for every subpath entry, by default.
http://jpauli.github.io/2014/06/30/realpath-cache.html
tl;dr PHP caches information from stat calls and it goes ahead and caches information about _every_ sub directory as well. This behavior could almost be seen as _helpful_ when using real system paths, and not fake paths with 4,000+ sub directories.<|eor|><|sor|>Actually why is PHP replicating the job of the OS? I'm pretty sure the OS already has some internal caching, and it's probably more efficient.<|eor|><|eoss|><|endoftext|> | 10 |
lolphp | theinvsblman | cvf1oat | <|soss|><|sot|>PHP's stat can actually be very expensive<|eot|><|sost|>Calling stat() on a path that contains many dots and double dots makes PHP perform an enormous amount of syscalls. Here's an [example PHP program](http://pastebin.com/KLPXb8jk) and its [strace output](https://gist.github.com/enneract/6a337c57dab6e8a4ba90). For comparison, the [equivalent C program](http://pastebin.com/9xNCZyR5) needs about 3 orders of magnitude less time to complete and [stats the path only once](http://pastebin.com/KsaJm6ew).
Could someone explain WTF is going on?
EDIT: I'm running PHP 5.6.13 (cli) on Linux x86_64.<|eost|><|sor|>> PHP resolves every paths it meets and splits every path part, resolving it. I explain : if you access the file "/home/julien/www/fooproject/app/web/entry.php", PHP is gonna split this path into as many single units as can fit. PHP is gonna resolve "/home", creating an entry for it into the cache. Then "/home/julien", then "/home/julien/www", etc.. Why this ? Well, first this is used to check access at every level of directory. Secondly, because many PHP users tend to build their pathnames using string concatenations, PHP may have a chance to have checked simple parts, it will then know if the user may access it or not, by asking the realpath cache for details. A cache hit is very cheap. The source code of tsrm_realpath_r() details the procedure. this is a recursive function which gets called for every subpath entry, by default.
http://jpauli.github.io/2014/06/30/realpath-cache.html
tl;dr PHP caches information from stat calls and it goes ahead and caches information about _every_ sub directory as well. This behavior could almost be seen as _helpful_ when using real system paths, and not fake paths with 4,000+ sub directories.<|eor|><|soopr|>It still doesn't fully explain the amount of syscalls. Why does PHP repeat the `lstat` calls a few times? (See my [other comment](https://www.reddit.com/r/lolphp/comments/3mg5kx/phps_stat_can_actually_be_very_expensive/cveptme) for a simpler case).<|eoopr|><|eoss|><|endoftext|> | 10 |
lolphp | headzoo | cveya9p | <|soss|><|sot|>PHP's stat can actually be very expensive<|eot|><|sost|>Calling stat() on a path that contains many dots and double dots makes PHP perform an enormous amount of syscalls. Here's an [example PHP program](http://pastebin.com/KLPXb8jk) and its [strace output](https://gist.github.com/enneract/6a337c57dab6e8a4ba90). For comparison, the [equivalent C program](http://pastebin.com/9xNCZyR5) needs about 3 orders of magnitude less time to complete and [stats the path only once](http://pastebin.com/KsaJm6ew).
Could someone explain WTF is going on?
EDIT: I'm running PHP 5.6.13 (cli) on Linux x86_64.<|eost|><|sor|>> PHP resolves every paths it meets and splits every path part, resolving it. I explain : if you access the file "/home/julien/www/fooproject/app/web/entry.php", PHP is gonna split this path into as many single units as can fit. PHP is gonna resolve "/home", creating an entry for it into the cache. Then "/home/julien", then "/home/julien/www", etc.. Why this ? Well, first this is used to check access at every level of directory. Secondly, because many PHP users tend to build their pathnames using string concatenations, PHP may have a chance to have checked simple parts, it will then know if the user may access it or not, by asking the realpath cache for details. A cache hit is very cheap. The source code of tsrm_realpath_r() details the procedure. this is a recursive function which gets called for every subpath entry, by default.
http://jpauli.github.io/2014/06/30/realpath-cache.html
tl;dr PHP caches information from stat calls and it goes ahead and caches information about _every_ sub directory as well. This behavior could almost be seen as _helpful_ when using real system paths, and not fake paths with 4,000+ sub directories.<|eor|><|eoss|><|endoftext|> | 9 |
lolphp | theinvsblman | cvewnnx | <|soss|><|sot|>PHP's stat can actually be very expensive<|eot|><|sost|>Calling stat() on a path that contains many dots and double dots makes PHP perform an enormous amount of syscalls. Here's an [example PHP program](http://pastebin.com/KLPXb8jk) and its [strace output](https://gist.github.com/enneract/6a337c57dab6e8a4ba90). For comparison, the [equivalent C program](http://pastebin.com/9xNCZyR5) needs about 3 orders of magnitude less time to complete and [stats the path only once](http://pastebin.com/KsaJm6ew).
Could someone explain WTF is going on?
EDIT: I'm running PHP 5.6.13 (cli) on Linux x86_64.<|eost|><|sor|>Does realpath() give the same results?<|eor|><|soopr|>PHP's realpath performs roughly the same amount of `lstat` syscalls as glibc's realpath (around 450-500), but glibc stats only "/tmp", whereas PHP stats very long paths (the strace log is almost 1 million characters long).<|eoopr|><|eoss|><|endoftext|> | 6 |
lolphp | barubary | 3llzd7 | <|sols|><|sot|>Assignment operator doesn't follow its own precedence rules<|eot|><|sol|>http://stackoverflow.com/questions/32672016/js-vs-php-assignment-operator-precedence-when-used-with-logical-or<|eol|><|eols|><|endoftext|> | 49 |
lolphp | satan-repents | cv7l3rr | <|sols|><|sot|>Assignment operator doesn't follow its own precedence rules<|eot|><|sol|>http://stackoverflow.com/questions/32672016/js-vs-php-assignment-operator-precedence-when-used-with-logical-or<|eol|><|sor|>> PHP manual also say Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.
Wait, what?<|eor|><|eols|><|endoftext|> | 24 |
lolphp | nikic | cv7u5zl | <|sols|><|sot|>Assignment operator doesn't follow its own precedence rules<|eot|><|sol|>http://stackoverflow.com/questions/32672016/js-vs-php-assignment-operator-precedence-when-used-with-logical-or<|eol|><|sor|>> PHP manual also say Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.
Wait, what?<|eor|><|soopr|>Many programming languages work the same way. Precedence tells you that `f() + g() * h()` parses as `f() + (g() * h())`, but it's unspecified which function is called first.<|eoopr|><|sor|>Shouldn't it be specified since the syntax is supposed to be unambiguous and the parse tree generated from a given expression will always be the same (ie like the boolean operators, where the order of evaluation is crucial)<|eor|><|sor|>You're thinking at the wrong level here. Precedence and associativity determine how the parse tree looks like, but the parse tree tells you nothing about the order in which things are evaluated. Think about something like `for (a; b; c) d;`. Here `a`, `b`, `c` and `d` will (probably) be the children of the `for` node, in this order. However, they will not be actually *run* in that order.
The same applies to expressions. While left-to-right evaluation is the most common case, the compiler is free to schedule execution in some kind of different order. For PHP in particular that provision in the documentation exists because, while evaluation is normally left-to-right, the compiler reserves the right to reorder certain variable reads.<|eor|><|eols|><|endoftext|> | 16 |
lolphp | barubary | cv7pl8i | <|sols|><|sot|>Assignment operator doesn't follow its own precedence rules<|eot|><|sol|>http://stackoverflow.com/questions/32672016/js-vs-php-assignment-operator-precedence-when-used-with-logical-or<|eol|><|sor|>> PHP manual also say Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.
Wait, what?<|eor|><|soopr|>Many programming languages work the same way. Precedence tells you that `f() + g() * h()` parses as `f() + (g() * h())`, but it's unspecified which function is called first.<|eoopr|><|eols|><|endoftext|> | 15 |
lolphp | edvo | cv7w328 | <|sols|><|sot|>Assignment operator doesn't follow its own precedence rules<|eot|><|sol|>http://stackoverflow.com/questions/32672016/js-vs-php-assignment-operator-precedence-when-used-with-logical-or<|eol|><|sor|>> PHP manual also say Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.
Wait, what?<|eor|><|soopr|>Many programming languages work the same way. Precedence tells you that `f() + g() * h()` parses as `f() + (g() * h())`, but it's unspecified which function is called first.<|eoopr|><|sor|>Shouldn't it be specified since the syntax is supposed to be unambiguous and the parse tree generated from a given expression will always be the same (ie like the boolean operators, where the order of evaluation is crucial)<|eor|><|sor|>The parse tree is unambiguous (hopefully), but the order of evaluation is not. For example if you have the expression `f() + g()` the interpreter might generate the following code:
$a = f()
$b = g()
$result = $a + $b
Or it might generate the following:
$b = g()
$a = f()
$result = $a + $b
Some languages make guarantees (e.g. that `f()` will always be called before `g()`), others do not.<|eor|><|eols|><|endoftext|> | 7 |
lolphp | barubary | cvl12ya | <|sols|><|sot|>Assignment operator doesn't follow its own precedence rules<|eot|><|sol|>http://stackoverflow.com/questions/32672016/js-vs-php-assignment-operator-precedence-when-used-with-logical-or<|eol|><|sor|>> $a || $a = 1;
Why would you ever write something like this? The OP even says "I use this all the time".<|eor|><|soopr|>Probably as a shorter version of
if (!$a) $a = 1;
to give variables a default value.<|eoopr|><|eols|><|endoftext|> | 5 |
lolphp | Rican7 | 247u3e | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|eoss|><|endoftext|> | 53 |
lolphp | deadstone | ch4hf6n | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>Knowing PHP, if they changed it, it would probably be de_Serialise().<|eor|><|eoss|><|endoftext|> | 45 |
lolphp | ajmarks | ch4kteb | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>Knowing PHP, if they changed it, it would probably be de_Serialise().<|eor|><|sor|>de_serialize_real() with some flags that make it dump variables into the namespace.<|eor|><|eoss|><|endoftext|> | 38 |
lolphp | ZorbaTHut | ch4pg0i | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>Knowing PHP, if they changed it, it would probably be de_Serialise().<|eor|><|sor|>de_serialize_real() with some flags that make it dump variables into the namespace.<|eor|><|sor|>For legacy reasons, this function accepts its parameters in any order.<|eor|><|eoss|><|endoftext|> | 38 |
lolphp | YouAintGotToLieCraig | ch4t1ut | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>Knowing PHP, if they changed it, it would probably be de_Serialise().<|eor|><|sor|>That's my favorite Counter-Strike map.<|eor|><|eoss|><|endoftext|> | 33 |
lolphp | catcradle5 | ch4k1kf | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>Knowing PHP, if they changed it, it would probably be de_Serialise().<|eor|><|sor|>serialize_de(
not to be confused with serialize_de_de because _de doesnt handle something right<|eor|><|sor|>And of course for German locales, `de_serialize_de_de()`.<|eor|><|eoss|><|endoftext|> | 24 |
lolphp | catcradle5 | ch4kcna | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>PHP needs a grammar/namespace fixing pass.
Take all the fucked up and inconsistent grammar and naming conventions in the php core, and fix it.
Alias the wrong functions to the correct one, with a deprecation warning.
<|eor|><|sor|>It needs a complete rewrite with little backward compatibility. Like Python 3 but more severe.
There's no chance it'll ever happen, but if the current core devs did a big overhaul without caring one bit about preserving compatibility, then the language could actually become *somewhat* bearable.<|eor|><|eoss|><|endoftext|> | 17 |
lolphp | ZorbaTHut | ch4pgm5 | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>PHP needs a grammar/namespace fixing pass.
Take all the fucked up and inconsistent grammar and naming conventions in the php core, and fix it.
Alias the wrong functions to the correct one, with a deprecation warning.
<|eor|><|sor|>It needs a complete rewrite with little backward compatibility. Like Python 3 but more severe.
There's no chance it'll ever happen, but if the current core devs did a big overhaul without caring one bit about preserving compatibility, then the language could actually become *somewhat* bearable.<|eor|><|sor|>Is PHP not open source? I'm honestly not sure, but if it is a project like that would probably take off quite rapidly.<|eor|><|sor|>It is, but if writing *in* PHP is this awful, just imagine what PHP's backend looks like.<|eor|><|eoss|><|endoftext|> | 17 |
lolphp | kageurufu | ch4jawj | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>Knowing PHP, if they changed it, it would probably be de_Serialise().<|eor|><|sor|>serialize_de(
not to be confused with serialize_de_de because _de doesnt handle something right<|eor|><|eoss|><|endoftext|> | 16 |
lolphp | frezik | ch554ks | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>Knowing PHP, if they changed it, it would probably be de_Serialise().<|eor|><|sor|>de_serialize_real() with some flags that make it dump variables into the namespace.<|eor|><|sor|>For legacy reasons, this function accepts its parameters in any order.<|eor|><|sor|>Unless they're named parameters. Then they have to appear in the order given.
(I actually had a command-line PHP program do this to me once.)<|eor|><|eoss|><|endoftext|> | 16 |
lolphp | kenlubin | ch4mqm2 | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>deserialize is grammatically valid (similar to decipher or decode), but unserialize is also grammatically valid (similar to undo or python's unpickle).<|eor|><|eoss|><|endoftext|> | 15 |
lolphp | suspiciously_calm | ch4wyeq | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>Knowing PHP, if they changed it, it would probably be de_Serialise().<|eor|><|sor|>That's my favorite Counter-Strike map.<|eor|><|sor|>The bomb has been planted. You have to de_serialize it.<|eor|><|eoss|><|endoftext|> | 15 |
lolphp | suspiciously_calm | ch4wyzg | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>That's unpossible!<|eor|><|eoss|><|endoftext|> | 11 |
lolphp | lisp-case | ch5603c | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>PHP needs a grammar/namespace fixing pass.
Take all the fucked up and inconsistent grammar and naming conventions in the php core, and fix it.
Alias the wrong functions to the correct one, with a deprecation warning.
<|eor|><|sor|>It needs a complete rewrite with little backward compatibility. Like Python 3 but more severe.
There's no chance it'll ever happen, but if the current core devs did a big overhaul without caring one bit about preserving compatibility, then the language could actually become *somewhat* bearable.<|eor|><|sor|>Is PHP not open source? I'm honestly not sure, but if it is a project like that would probably take off quite rapidly.<|eor|><|sor|>It is, but if writing *in* PHP is this awful, just imagine what PHP's backend looks like.<|eor|><|sor|>I don't have to imagine it. At one point after realizing the documentation on type-juggling is incomplete, I decided it would be a *great* idea to actually read the source so I knew what was actually going on.
It started at macros that inject `return`s into their expansion site and got worse.<|eor|><|eoss|><|endoftext|> | 9 |
lolphp | kenlubin | ch4ry6y | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>PHP needs a grammar/namespace fixing pass.
Take all the fucked up and inconsistent grammar and naming conventions in the php core, and fix it.
Alias the wrong functions to the correct one, with a deprecation warning.
<|eor|><|sor|>It needs a complete rewrite with little backward compatibility. Like Python 3 but more severe.
There's no chance it'll ever happen, but if the current core devs did a big overhaul without caring one bit about preserving compatibility, then the language could actually become *somewhat* bearable.<|eor|><|sor|>Is PHP not open source? I'm honestly not sure, but if it is a project like that would probably take off quite rapidly.<|eor|><|sor|>PHP is open source, but a breaking-compatability overhaul would not take off at all. Look at python3. It's been six years and people are still arguing about whether or not it's worth migrating. php is bigger and more entrenched with more backward compatibility to deal with, and the project wouldn't be led by Rasmus or Guido.<|eor|><|eoss|><|endoftext|> | 8 |
lolphp | poloppoyop | ch5uznp | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>PHP needs a grammar/namespace fixing pass.
Take all the fucked up and inconsistent grammar and naming conventions in the php core, and fix it.
Alias the wrong functions to the correct one, with a deprecation warning.
<|eor|><|sor|>It needs a complete rewrite with little backward compatibility. Like Python 3 but more severe.
There's no chance it'll ever happen, but if the current core devs did a big overhaul without caring one bit about preserving compatibility, then the language could actually become *somewhat* bearable.<|eor|><|sor|>> Like Python 3
Tell me, what is the adoption rate of Python 3 6 years after it was released?<|eor|><|eoss|><|endoftext|> | 7 |
lolphp | Astr4c | ch6s7a1 | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>There's no real reason to use it over JSON (which uses json_encode and json_decode). JSON is faster in modern PHP versions, it's much easier to read, and there's less security risks. Serialised data stores the class names of serialised objects so anyone that can modify serialised data can instantiate arbitrary classes. <|eor|><|sor|>There are big libraries relying on the fact that you can change the class using the serializer. Doctrine (an ORM inspired to Hybernate) use the unserialize hack to create entity instances without using calling the constructor when hydrating a result from the database.
Knowing this makes me feel dirty.
EDIT: To be clear, from Doctrine sources:
$this->_prototype = unserialize(sprintf('O:%d:"%s":0:{}', strlen($this->name), $this->name));<|eor|><|eoss|><|endoftext|> | 6 |
lolphp | hylje | ch5sagq | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>PHP needs a grammar/namespace fixing pass.
Take all the fucked up and inconsistent grammar and naming conventions in the php core, and fix it.
Alias the wrong functions to the correct one, with a deprecation warning.
<|eor|><|sor|>It needs a complete rewrite with little backward compatibility. Like Python 3 but more severe.
There's no chance it'll ever happen, but if the current core devs did a big overhaul without caring one bit about preserving compatibility, then the language could actually become *somewhat* bearable.<|eor|><|sor|>>It needs a complete rewrite with little backward compatibility.
We already have that. It's called Perl. Or Python. I think Ruby is up there too.<|eor|><|eoss|><|endoftext|> | 6 |
lolphp | kageurufu | ch4k8xv | <|soss|><|sot|> Dear god. Today I just realized that #php's `unserialize()` is grammatically incorrect. It should be `deserialize()`.<|eot|><|sost|><|eost|><|sor|>Knowing PHP, if they changed it, it would probably be de_Serialise().<|eor|><|sor|>serialize_de(
not to be confused with serialize_de_de because _de doesnt handle something right<|eor|><|sor|>And of course for German locales, `de_serialize_de_de()`.<|eor|><|sor|>exactly!<|eor|><|eoss|><|endoftext|> | 6 |
lolphp | n1c0_ds | 1zpxkl | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|eols|><|endoftext|> | 53 |
lolphp | zeus_is_back | cfvynad | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>PHP has 10,000+ loose functions built in, but you still have to roll your own for even the most basic things.<|eor|><|eols|><|endoftext|> | 31 |
lolphp | PhantomRacer | cfw8kq6 | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>> These functions will return false for a string, even if it contains an integer.
Strings can't contain integers, they can only contains strings of characters. PHP's loose typing will allow you to cast a string to an integer in some cases, but it's still a string. If you want to reliably check for integers in PHP use **is_int**.<|eor|><|eols|><|endoftext|> | 22 |
lolphp | senatorpjt | cfw0um0 | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>is regex that slow? I think if your code is performance-sensitive enough that using a regex would cause significant issues, you probably shouldn't be using PHP to begin with. <|eor|><|eols|><|endoftext|> | 20 |
lolphp | Innominate8 | cfwj077 | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>is regex that slow? I think if your code is performance-sensitive enough that using a regex would cause significant issues, you probably shouldn't be using PHP to begin with. <|eor|><|sor|>I enjoy that the simplest, quickest and easiest solution is dismissed with what is essentially "I don't understand regular expressions."
A regex for that is a short fairly simple pattern that is a hell of a lot better than the mess he came up with.<|eor|><|eols|><|endoftext|> | 19 |
lolphp | ahruss | cfwm2te | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>is regex that slow? I think if your code is performance-sensitive enough that using a regex would cause significant issues, you probably shouldn't be using PHP to begin with. <|eor|><|sor|>I enjoy that the simplest, quickest and easiest solution is dismissed with what is essentially "I don't understand regular expressions."
A regex for that is a short fairly simple pattern that is a hell of a lot better than the mess he came up with.<|eor|><|sor|> ^[+-]?\d+$
That was hard. <|eor|><|eols|><|endoftext|> | 15 |
lolphp | ahruss | cfwhwa6 | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>> These functions will return false for a string, even if it contains an integer.
Strings can't contain integers, they can only contains strings of characters. PHP's loose typing will allow you to cast a string to an integer in some cases, but it's still a string. If you want to reliably check for integers in PHP use **is_int**.<|eor|><|sor|>Exactly. It would be a lolphp if `is_int($someString)` returned true. <|eor|><|eols|><|endoftext|> | 12 |
lolphp | vita10gy | cfw20i1 | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>PHP has 10,000+ loose functions built in, but you still have to roll your own for even the most basic things.<|eor|><|sor|>I hate php, but I've been using it part or full time for like a decade now and I've never had to do this. So, although it might sound trivial to need something that is "really extra super sure" whatever is an int, I'm not sure it would be accurate to call the need for this a "most basic" thing. Cleaning input to what you want is pretty unique to the situation. "123 " isn't an int, so why should it pass? <|eor|><|eols|><|endoftext|> | 10 |
lolphp | vita10gy | cfw6216 | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>PHP has 10,000+ loose functions built in, but you still have to roll your own for even the most basic things.<|eor|><|sor|>I hate php, but I've been using it part or full time for like a decade now and I've never had to do this. So, although it might sound trivial to need something that is "really extra super sure" whatever is an int, I'm not sure it would be accurate to call the need for this a "most basic" thing. Cleaning input to what you want is pretty unique to the situation. "123 " isn't an int, so why should it pass? <|eor|><|soopr|>It should not, and it does not. However, I'd expect is_int to see "123" as an int, since is_numeric handles strings just fine. I'd also expect PHP not to cast anything under the sun without barfing, but that's not the case.
The scenario is simple: you are given a value from an unknown source, and that value can only be a positive or negative integer. It could be "days since *", "number of apples in my possession" etc.
If the user entered 0x24, chances are that he didn't mean it to be a number, and therefore it should not be valid input.<|eoopr|><|sor|>But that's not the question you're asking is_int. It's "is" not "could this be". is_numeric is a less specific question, so you can get a different answer. if is_int said yes to "123" then people would lol at that and wonder how to check 123 vs "123". One is a very direct very specific question, one is "does this thing look numberish?"
PHP has lots of issues, I'm just not sure that "look you call different functions with the same thing and you get different answers!" is one of them. Because, duh. That's why there are options. If it did return the same thing people would roll their eyes at it having 5 redundant functions. PHP has tons of problems, but sometimes it seems damned if it does and damned if it doesn't.
You'll get no argument here though that PHP's magic type conversion causes as many problems as it saves though. I'm just not sure there's a way everything one could want in all contexts could be done. A function along the line of:
Returns cleaned number based on the input passed in, returns false if
$mixed can not be represented as a number
mixed clean_numeric_input($mixed, $only_allow_int = false, $allow_negative=false,
$allow_hexidecimal = false, $allow_exponents=false)
Are always among the shittiest PHP has to offer. There's always something else it needs to do, more parameters (or worse NONSENSICAL_FLAGS && TO_SET && THAT_ARENT_ACTUALLY_LISTED_ANYWHERE) it needs to cover your situation anyway.
Is "0x24" a 0? an error? a 24? It's all so context sensitive, and there's never a great way to handle these "garbage in garbage out" situations if you KNOW the context, let alone one global "this is how to convert 'I have 5 dogs and 4 cats' to an int".
What this person has isn't even terribly helpful because a yes/no "this could be an int" doesn't actually convert the garbage to a number. If you cleaned it up first, which you have to do anyway, and THEN check, some of these issues go away.<|eor|><|eols|><|endoftext|> | 10 |
lolphp | sickofthisshit | cfwtrk7 | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>> These functions will return false for a string, even if it contains an integer.
Strings can't contain integers, they can only contains strings of characters. PHP's loose typing will allow you to cast a string to an integer in some cases, but it's still a string. If you want to reliably check for integers in PHP use **is_int**.<|eor|><|soopr|>I was talking about integers as a value, not as a data type. Since there PHP will cast just about anything, you can't just blindly cast the data.<|eoopr|><|sor|>The point is that a string never "is" a number "as a value." It is just a sequence of characters that some human or computer might understand as a number according to defined rules.<|eor|><|eols|><|endoftext|> | 9 |
lolphp | ahruss | cfwvf3o | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>is regex that slow? I think if your code is performance-sensitive enough that using a regex would cause significant issues, you probably shouldn't be using PHP to begin with. <|eor|><|sor|>I enjoy that the simplest, quickest and easiest solution is dismissed with what is essentially "I don't understand regular expressions."
A regex for that is a short fairly simple pattern that is a hell of a lot better than the mess he came up with.<|eor|><|sor|>I don't think that's why it's dismissed at all.
For any other language, using a *regex* to verify if a *string is numerical* sounds utterly absurd. Only in PHP is that considered actually a kind of reasonable thing to do.<|eor|><|sor|>How is that crazy? What would you do in another language? This is something regex is awesome at. Granted, *some* languages have builtin functions for it, but not all of them. <|eor|><|eols|><|endoftext|> | 9 |
lolphp | Serialk | cfy56gg | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>is regex that slow? I think if your code is performance-sensitive enough that using a regex would cause significant issues, you probably shouldn't be using PHP to begin with. <|eor|><|sor|>I enjoy that the simplest, quickest and easiest solution is dismissed with what is essentially "I don't understand regular expressions."
A regex for that is a short fairly simple pattern that is a hell of a lot better than the mess he came up with.<|eor|><|sor|>I don't think that's why it's dismissed at all.
For any other language, using a *regex* to verify if a *string is numerical* sounds utterly absurd. Only in PHP is that considered actually a kind of reasonable thing to do.<|eor|><|sor|>How is that crazy? What would you do in another language? This is something regex is awesome at. Granted, *some* languages have builtin functions for it, but not all of them. <|eor|><|sor|>On Python you could do it with a generator comprehension, like:
def is_integer(value):
return value[0] in '+-0123456789' and all(x in '0123456789'
for x in value[1:])
On Clojure: (I'm a total Clojure noob so there's probably a better way to do it)
(defn in? [elem coll]
(boolean (some #{elem} coll)))
(defn integer? [value]
(let [digits #{\0 \1 \2 \3 \4 \5 \6 \7 \8 \9}
digits-plus-minus (concat digits #{\+ \-})]
(and
(in? (first value) digits-plus-minus)
(every? #(in? % digits) (rest value)))))<|eor|><|sor|>This is absurd. Compiled regular expressions would work even *faster*.
Edit: I can prove it: http://codepad.org/zS4N703a<|eor|><|eols|><|endoftext|> | 9 |
lolphp | Rainfly_X | cfvxvyj | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>One of the fonts is broken, and I 90% of this page is empty space.<|eor|><|eols|><|endoftext|> | 8 |
lolphp | rcxdude | cfy8an7 | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>is regex that slow? I think if your code is performance-sensitive enough that using a regex would cause significant issues, you probably shouldn't be using PHP to begin with. <|eor|><|sor|>I enjoy that the simplest, quickest and easiest solution is dismissed with what is essentially "I don't understand regular expressions."
A regex for that is a short fairly simple pattern that is a hell of a lot better than the mess he came up with.<|eor|><|sor|>I don't think that's why it's dismissed at all.
For any other language, using a *regex* to verify if a *string is numerical* sounds utterly absurd. Only in PHP is that considered actually a kind of reasonable thing to do.<|eor|><|sor|>How is that crazy? What would you do in another language? This is something regex is awesome at. Granted, *some* languages have builtin functions for it, but not all of them. <|eor|><|sor|>On Python you could do it with a generator comprehension, like:
def is_integer(value):
return value[0] in '+-0123456789' and all(x in '0123456789'
for x in value[1:])
On Clojure: (I'm a total Clojure noob so there's probably a better way to do it)
(defn in? [elem coll]
(boolean (some #{elem} coll)))
(defn integer? [value]
(let [digits #{\0 \1 \2 \3 \4 \5 \6 \7 \8 \9}
digits-plus-minus (concat digits #{\+ \-})]
(and
(in? (first value) digits-plus-minus)
(every? #(in? % digits) (rest value)))))<|eor|><|sor|>This is absurd. Compiled regular expressions would work even *faster*.
Edit: I can prove it: http://codepad.org/zS4N703a<|eor|><|sor|>Indeed. statements like 'this would be too slow' (where the algorithmic complexity is the same) should be accompanied by data like this.<|eor|><|eols|><|endoftext|> | 7 |
lolphp | djsumdog | cfw7cpz | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>PHP has 10,000+ loose functions built in, but you still have to roll your own for even the most basic things.<|eor|><|sor|>I hate php, but I've been using it part or full time for like a decade now and I've never had to do this. So, although it might sound trivial to need something that is "really extra super sure" whatever is an int, I'm not sure it would be accurate to call the need for this a "most basic" thing. Cleaning input to what you want is pretty unique to the situation. "123 " isn't an int, so why should it pass? <|eor|><|sor|>Database issues. If I'm using Squeryl in Scala or Active Record in ruby or even plain old JDBC in Java, the database, I know if I use those language conversion functions and I get scalar or even an object that as a type of int/Integer, I know that SQL function will take that type in as a parameter and not barf.
Now maybe there is some janky stuff in each languages type conversion libraries you don't like and it might convert some odd strings into Ints you don't think should be ints, but that's another issue. A lot of people write and use other validation frameworks (Play, Spring MVC, etc have validation frameworks for web inputs). But the thing is, so long as it makes it into an Integer, and the JDBC drivers aren't buggy, I know the database code/logic will be safe.
You don't get that guarantee in PHP.<|eor|><|eols|><|endoftext|> | 6 |
lolphp | catcradle5 | cfwmbv6 | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>is regex that slow? I think if your code is performance-sensitive enough that using a regex would cause significant issues, you probably shouldn't be using PHP to begin with. <|eor|><|sor|>I enjoy that the simplest, quickest and easiest solution is dismissed with what is essentially "I don't understand regular expressions."
A regex for that is a short fairly simple pattern that is a hell of a lot better than the mess he came up with.<|eor|><|sor|>I don't think that's why it's dismissed at all.
For any other language, using a *regex* to verify if a *string is numerical* sounds utterly absurd. Only in PHP is that considered actually a kind of reasonable thing to do.<|eor|><|eols|><|endoftext|> | 6 |
lolphp | gavintlgold | cfvygyn | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>One of the fonts is broken, and I 90% of this page is empty space.<|eor|><|sor|>Refreshing the page fixed that for me.<|eor|><|eols|><|endoftext|> | 5 |
lolphp | vita10gy | cfwkce7 | <|sols|><|sot|>This is how you reliably check for an integer in PHP<|eot|><|sol|>http://wisercoder.com/check-for-integer-in-php/<|eol|><|sor|>PHP has 10,000+ loose functions built in, but you still have to roll your own for even the most basic things.<|eor|><|sor|>I hate php, but I've been using it part or full time for like a decade now and I've never had to do this. So, although it might sound trivial to need something that is "really extra super sure" whatever is an int, I'm not sure it would be accurate to call the need for this a "most basic" thing. Cleaning input to what you want is pretty unique to the situation. "123 " isn't an int, so why should it pass? <|eor|><|sor|>> I hate php, but I've been using it part or full time for like a decade now and I've never had to do this.
If you've literally *never* had to do this then odds are you've implemented some pretty serious bugs.<|eor|><|sor|>Or I don't back myself into these kinds of corners in the first place.<|eor|><|eols|><|endoftext|> | 5 |
lolphp | NotSantaAtAll | 1ist19 | <|sols|><|sot|>echo ++$a + $a++; // may print 4 or 5<|eot|><|sol|>http://php.net/manual/en/language.operators.precedence.php#example-114<|eol|><|eols|><|endoftext|> | 50 |
lolphp | tdammers | cb7oxqf | <|sols|><|sot|>echo ++$a + $a++; // may print 4 or 5<|eot|><|sol|>http://php.net/manual/en/language.operators.precedence.php#example-114<|eol|><|sor|>This is something PHP more or less inherits directly from C, where the following is undefined as well:
int i = 1;
i = ++i + i++;
printf("%i\n", i);<|eor|><|eols|><|endoftext|> | 39 |
lolphp | barubary | cb7puti | <|sols|><|sot|>echo ++$a + $a++; // may print 4 or 5<|eot|><|sol|>http://php.net/manual/en/language.operators.precedence.php#example-114<|eol|><|sor|>This is something PHP more or less inherits directly from C, where the following is undefined as well:
int i = 1;
i = ++i + i++;
printf("%i\n", i);<|eor|><|sor|>The difference is that apparently in PHP the result is restricted to 4 or 5. In C, you don't just get an unspecified number, you get completely undefined behavior, i.e. according to the C standard the code is literally meaningless and any behavior is "correct".
So the code could:
* output 4
* output 5
* output "hello, world"
* run minesweeper
* crash
* delete random files
* make demons fly out of your nose
Optimizers will often assume that undefined behavior can't happen and therefore eliminate all code that could only lead to undefined behavior.
TL;DR: C compilers are in fact out to get you.<|eor|><|eols|><|endoftext|> | 35 |
lolphp | Drainedsoul | cb7pjxl | <|sols|><|sot|>echo ++$a + $a++; // may print 4 or 5<|eot|><|sol|>http://php.net/manual/en/language.operators.precedence.php#example-114<|eol|><|sor|>If this is "*lolphp*" it's also "*lolc*" and "*lolc++*" too.
Undefined behaviour isn't "*lol*", it's -- in many cases -- necessary or preferable so that the compiler (or, I guess, interpreter in this case) can do a good job in a wide variety of cases.<|eor|><|eols|><|endoftext|> | 28 |
lolphp | djsumdog | cb7psu6 | <|sols|><|sot|>echo ++$a + $a++; // may print 4 or 5<|eot|><|sol|>http://php.net/manual/en/language.operators.precedence.php#example-114<|eol|><|sor|>If this is "*lolphp*" it's also "*lolc*" and "*lolc++*" too.
Undefined behaviour isn't "*lol*", it's -- in many cases -- necessary or preferable so that the compiler (or, I guess, interpreter in this case) can do a good job in a wide variety of cases.<|eor|><|sor|>I agree to a point, but I also see the case where if you have a higher level language, you should provide more consistency.
The reason that happens in C is due to the compiler parse tree. gcc, icc and HP's c compiler all break statements apart differently and may execute things in an order you don't expect.
But when you use a language like Java/Python/Ruby, you expect the interpreter to not just be a thin C wrapper and have its own parsing system. So even if the results are weird or quirky, at least they'd be consistent across multiple platforms. <|eor|><|eols|><|endoftext|> | 16 |
lolphp | phoshi | cb7wu2y | <|sols|><|sot|>echo ++$a + $a++; // may print 4 or 5<|eot|><|sol|>http://php.net/manual/en/language.operators.precedence.php#example-114<|eol|><|sor|>If this is "*lolphp*" it's also "*lolc*" and "*lolc++*" too.
Undefined behaviour isn't "*lol*", it's -- in many cases -- necessary or preferable so that the compiler (or, I guess, interpreter in this case) can do a good job in a wide variety of cases.<|eor|><|sor|>No, this is a lolphp. C/C++ have undefined behaviour for a lot of reasons, easier compiler optimisations or massive portability being some of them, but... PHP doesn't compile down to machine code, so the portability benefit is out of the window, and it sure as fuck doesn't produce highly optimised code. It's taking the disadvantages of undefined behaviour without granting the advantages, which is the real lol.<|eor|><|eols|><|endoftext|> | 15 |
lolphp | farsightxr20 | cb8c614 | <|sols|><|sot|>echo ++$a + $a++; // may print 4 or 5<|eot|><|sol|>http://php.net/manual/en/language.operators.precedence.php#example-114<|eol|><|sor|>> // mixing ++ and + produces undefined behavior
PHP has defined behavior? Where can I find the spec?<|eor|><|eols|><|endoftext|> | 14 |
lolphp | InconsiderateBastard | cb7twlk | <|sols|><|sot|>echo ++$a + $a++; // may print 4 or 5<|eot|><|sol|>http://php.net/manual/en/language.operators.precedence.php#example-114<|eol|><|sor|>Wait, why would that output 5?
$b = ++$a; echo $b + $a++; --> 2 + 2 = 4
$b = $a++; echo ++$a + $b; --> 3 + 1 = 4<|eor|><|sor|>Because undefined behavior. It could output "( " if it wanted to.<|eor|><|eols|><|endoftext|> | 13 |
lolphp | dipswitch | cb7yh1m | <|sols|><|sot|>echo ++$a + $a++; // may print 4 or 5<|eot|><|sol|>http://php.net/manual/en/language.operators.precedence.php#example-114<|eol|><|sor|>Wait, why would that output 5?
$b = ++$a; echo $b + $a++; --> 2 + 2 = 4
$b = $a++; echo ++$a + $b; --> 3 + 1 = 4<|eor|><|sor|>Because undefined behavior. It could output "( " if it wanted to.<|eor|><|sor|>As opposed to errors in hebrew (unexpected T_PAAMAYIM_NEKUDOTAYIM?), that would be an improvement.<|eor|><|eols|><|endoftext|> | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.