Working With PHP Data Types - Manipulating a variables data type
(Page 3 of 5 )
PHP includes a great function, gettype that we can use to display the type of a variable, and not its actual value. You can use gettype like this:
<?
$i = 10;
$j = 10.3;
$k = "Broncos";
echo(gettype($i) . "<br>"); // Displays the string "integer"
echo(gettype($j) . "<br>"); // Displays the string "double"
echo(gettype($k) . "<br>"); // Displays the string "string"
?>Notice our use of the period operator to separate our call to the gettype function from the HTML code contained within the quotes for each echo function. By simply changing the variable we pass as the parameter to the gettype function, we can check the data type of any other variable. We can also set the data type of a variable after it has been created. The following example first defines a double, and uses PHP's settype function to redefine it to an integer.
<?
$k = 12.1;
echo("$k = " . gettype($k) . "<br>"); // Displays "$k = double"
settype($k, "integer"); // Changes the data type of variable k
echo("$k now = " . gettype($k)); // Displays "$k now = integer"
?>As you can see, we are actually passing in two different parameters to the settype function: the name of the variable whose type we want to change, and the variable type we want to change it to. Keep in mind that if you change a string to an integer, then the value of that string will equal 0, instead of the actual string of characters that it was initially defined to hold.
Next: If this, if that >>
More PHP Articles
More By Steve Adcock