Learn PHP:12-Changing Data Types

Posted: November 3, 2010 in PHP
Tags:

PHP has loose data typing. Because of this, changing a variable’s data type is not a commonly used mechanism in PHP due to the fact that PHP will automatically cast your variable types when your script changes to use the variable as a different type and in a different way.

As illustrated in this sample code:

 <?php
$var1 = "18 years old";
$var2 = "14 years old";
// Since PHP knows that it cannot add two strings mathematically it automatically
// removes the string parts of the variables and proceeds to do the math correctly
$sumOfBoth = $var1 + $var2;
// Very interesting that we get such a result and not an error
echo $sumOfBoth;
?>


The Browser is shown like below :

32

But let’s say we have created a form. And in that form we want to know how many gigabytes our client’s hard drive is. In entering the value they placed the size number and bytes characters like this “250gb”, but we just wanted the number. If we try to then output or store just the number our plans are foiled because the client put the “gb” characters in there. Illustrated in this sample code:

<?php
// Let's say this is the value we wind up with from the form input
$var1 = "250gb";

echo "You stated that your Hard Drive size capacity is " . $var1 . " Gigabytes";
?>

The browser is shown like below :

You stated that your Hard Drive size capacity is 250gb Gigabytes

Use the settype() function to change data types :

 

<?php
// Same variable and value
$var1 = "250gb";
// This time use settype() and claim integer as the data type
settype($var1, 'integer');

echo "You stated that your Hard Drive size capacity is " . $var1 . " Gigabytes";
?>

The output is shown like below :

You stated that your Hard Drive size capacity is 250 Gigabytes

Use Type Casting to change data types :

 <?php
// Same variable and value
$var1 = "250gb";
// This time use type casting and claim integer as the data type
$var1 = (integer) $var1;

echo "You stated that your Hard Drive size capacity is " . $var1 . " Gigabytes";
?>

 

The output is shown like below :

You stated that your Hard Drive size capacity is 250 Gigabytes

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s