Menu

A thought about PHP's string-to-number conversions

#php#redditr#unreliable#value#reliable
Reading 0:00
15s threshold

Hello,

I have always found PHPs string to number conversions a bit odd. Classic example:

php $value = (int)"32px"; // 32 $value = (int)"kg32"; // 0

I know this is intentional, and sometimes it is useful.

But.. you can get a perfectly valid integer, and the informatino that original string contained something important(or not) is gone.

I was thinking about a way to deal with this and came up with an idea:

What about attaching a reliable / unreliable flag to values?

Imagine that PHP engine could attach special runtime flags to any value; For example, the runtime could automatically mark a value as unreliable when conversion is questionable.

The flag would follow the value through assignments and calculations:

php $a = (int)"32kg"; // 32, unreliable $b = $a * 2; // 64, still unreliable $c = $b + 10; // 74, still unreliable

This flag can be set or clear explicitly:

php $a = (unreliable)42; $a = (reliable)$a;

Normally the flag does not affect anything. Your code would run as usual.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.