5

Im trying to get the variable type but I dont know why, always says that the variable is a string.

Here is my object:

$question

stdClass Object
        (
            [reply_id] => 8
            [q_key] => 35BBs2xy1346230680
            [answer] => 1
        )


echo $question->answer." is a ".gettype($question->answer);

The output is:

1 is a string

But 1 is a integer...

What am I doing wrong ?

j0k
  • 22,600
  • 28
  • 79
  • 90
Klian
  • 1,520
  • 5
  • 21
  • 32
  • 1
    Do you want to know if the type is technically an integer or if the scalar value only contains digits? Also, please print the object using `var_dump()`. – Daniel M Sep 05 '12 at 15:50
  • 2
    If it says it's a string, then it's a string. Where does the data come from for you to think it's not a string? – deceze Sep 05 '12 at 15:56

4 Answers4

5

If the value was passed from a $_GET or $_POST then it was automatically treated as a string. If it was returned from a mysql query it is being returned as a string.

At best, you can use settype to set it to an integer. Having said that, PHP is pretty liberal when it comes to types and their values.

Example of settype:

<?php
$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo is now 5   (integer)
settype($bar, "string");  // $bar is now "1" (string)
?>

Notes from Types:

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.

Community
  • 1
  • 1
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
1

Im using EZsql to get the object... I'm not defining the variable. I think is_numeric() function will do the job :)

Thanks!

Klian
  • 1,520
  • 5
  • 21
  • 32
0

This is because of the way you assign this variable. Here's the example:

$a = 1;
var_dump($a);
$a = "1";
var_dump($a);

which would produce:

int(1)
string(1) "1"
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
0

You did not define it as a string, rather than define it this way:

$question->answer = 1;

You need to define it thusly:

$question->answer = "1";

PHP also works with implicit variables, so it may automatically declare a numeric answer as an integer. To remedy this, if $var = "1", define it this way:

$question->answer = strval($var);
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
Sommer
  • 61
  • 3