a coder
a coder

Reputation: 7659

Convert string to integer?

I'm pulling results from an XML file and one of the values (an actual numeric ID) is being read as a string. The value is trimmed and has no whitespace. I observed this by checking with is_numeric:

        if (!is_numeric($id))
        {
            echo "<p>$id is NOT numeric";
        } else {
            echo "<p>$id is numeric";
        }

The response of a variable 643394 is:

643394 is NOT numeric

PHP has a function to convert an integer to a string (strtoint), but I didn't find a function to go the other way (inttostr).

Is it possible to convert string "1234" to integer 1234?

Upvotes: 1

Views: 4791

Answers (3)

Daydiff
Daydiff

Reputation: 21

This is will help you:

$id = $id + 0;

Upvotes: 0

Waygood
Waygood

Reputation: 2683

String to integer conversion can be done with intval($id) or force an integer type with (int)$id

Upvotes: 1

j08691
j08691

Reputation: 208002

Cast your string to an integer explicitly

$id = (int) $id;

ref: http://php.net/manual/en/language.types.type-juggling.php

Upvotes: 7

Related Questions