0

What are the conversion rules for strings to ints in PHP?

For example I have the following that return 0:

var_dump((int)"test0");
var_dump((int)"test1");
var_dump((int)"test2");

and it appears that if the string starts with a digit then it will trim the characters and use the digit part only. As follows:

var_dump((int)"1test");
var_dump((int)"2test");
var_dump((int)"3test");

These return 1, 2 and 3 respectively.

Now, is this a definite rule, or are there exceptions to this?

1 Answer 1

5

This is explained in PHP's manual:

http://php.net/manual/en/language.types.string.php#language.types.string.conversion

An excerpt:

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.