1

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?

a coder
  • 7,530
  • 20
  • 84
  • 131

3 Answers3

7

Cast your string to an integer explicitly

$id = (int) $id;

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

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    May I ask what the benefit of using this advantage is over using `intval()`? – VictorKilo Aug 16 '12 at 16:29
  • 1
    @VictorKilo - According to https://wiki.phpbb.com/Best_Practices:PHP, using a function for conversion is slightly slower than directly casting. For a further explanation, see http://stackoverflow.com/questions/5339590/when-should-one-use-intval-and-when-int – j08691 Aug 16 '12 at 16:32
1

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

Waygood
  • 2,657
  • 2
  • 15
  • 16
0

This is will help you:

$id = $id + 0;
Daydiff
  • 21
  • 1