3 ms·
Should a string, when converted to an integer, become 1, not 0? (Unless it is a string of only digits, like "567". Then it should become 567.) (bool) 'x' //
by combatentropy 6y ago
Should a string, when converted to an integer, become 1, not 0? (Unless it is a string of only digits, like "567". Then it should become 567.)
(bool) 'x' // true
(int) true // 1
If a string is truthy in a boolean situation, shouldn't it also be truthy in a numeric one?
The types form a hierarchy in my mind, from simple to complex: from boolean to integer, to float, to string, to compound types like arrays and objects. It seems like values should cast up and down the chain uniformly.
- darthrupert 6y agoThese are easy questions. 1. If you convert a string which has non-numbers to an integer, an error is raised 2. Truthiness should not exist as a concept. Just booleans and expressions that evaluate to booleans. PHP's backwards compatibilty promise makes these more difficult questions, of course.
- pavlov 6y agoEasy questions but not obvious answers. What kind of error to raise? Do you return a NaN? Throw an exception? Both have their uses.
- darthrupert 6y agoThrow a standard exception. E.g. python calls it a ValueError. Returing NaN is clearly wrong design.
- Erlich_Bachman 6y ago> 2. Truthiness should not exist as a concept. Meh, it's actually quite useful in many situations.