MattS
MattS

Reputation: 727

PHP Using a string in arithmetic

I have situation where I have a variable being used in some arithmetic (mostly just multiplication/division) in a PHP function. The variable is actually passed to the function from another. What gets passed, though, may be either a numerical value, or a string value.

So basically I have:

 $inverse = 1/$number;

Where $number may be either a valid number, or a string.

My question is what happens when $number is a string? How does php handle that situation?

Ultimately the answer isn't too important; I can think of a couple of different ways of working around the situation. It's just that it came up, I got curious, and a quick google search couldn't answer my question. Even if I don't need to know the answer, I'd like to know the answer, because understanding how PHP works will help me in the future.

Thanks.

Upvotes: 1

Views: 1704

Answers (3)

Shoe
Shoe

Reputation: 76300

It will take the string and will analize it's aritmetic value: for example "1bottle" will became 1. The general rule is that every numeric char inside the first part of the string is converted to float. So 12.3bottle = 12.3, .3alonin = 0.3, and so on. If there's no first numeric chars then the value will be 0.

This is called type juggling.

Upvotes: 1

nickb
nickb

Reputation: 59709

PHP will perform type-coercion (also known as type-juggling) and attempt to interpret the value as a number when it is a string when the variable is used in a numerical context.

See the docs on the division operator:

The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned.

Also relevant, String conversions to a number:

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

....

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

Upvotes: 3

Antimony
Antimony

Reputation: 39471

PHP silently converts the string to a floating point number.

Upvotes: 1

Related Questions