Searching...
Thursday 13 June 2013

PHP Basics - Part 4 :: continued


Converting Between Data Types Using Type Casting


Converting values from one datatype to another is known as type casting. A variable can be evaluated once as a different type by casting it to another. This is accomplished by placing the intended type in front of the variable to be cast. A type can be cast by inserting one of the operators (shown in Table) in front of the variable.

Type Casting Operators
Type Casting Operators

Let’s consider several examples. Suppose you’d like to cast an integer as a double:

$score = (double) 13; // $score = 13.0

Type casting a double to an integer will result in the integer value being rounded down, regardless of the decimal value. Here’s an example:

$score = (int) 14.8; // $score = 14

What happens if you cast a string datatype to that of an integer? Let’s find out:

$sentence = "This is a sentence";
echo (int) $sentence; // returns 0

While likely not the expected outcome, it’s doubtful you’ll want to cast a string like this anyway.
You can also cast a datatype to be a member of an array. The value being cast simply becomes the first element of the array:

$score = 1114;
$scoreboard = (array) $score;
echo $scoreboard[0]; // Outputs 1114

Note: This shouldn't be considered standard practice for adding items to an array because this only seems to work for the very first member of a newly created array. If it is cast against an existing array, that array will be wiped out, leaving only the newly cast value in the first position.

One final example: any datatype can be cast as an object. The result is that the variable becomes an attribute of the object, the attribute having the name scalar:

$model = "Toyota";
$obj = (object) $model;

The value can then be referenced as follows:

print $obj->scalar; // returns "Toyota"


Adapting Data Types with Type Juggling

Because of PHP’s lax attitude toward type definitions, variables are sometimes automatically cast to best fit the circumstances in which they are referenced. Consider the following snippet:

<?php
$total = 5; // an integer
$count = "15"; // a string
$total += $count; // $total = 20 (an integer)
?>

The outcome is the expected one; $total is assigned 20, converting the $count variable from a string to an integer in the process. Here’s another example demonstrating PHP’s type-juggling capabilities:

<?php
$total = "45 fire engines";
$incoming = 10;
$total = $incoming + $total; // $total = 55
?>


The integer value at the beginning of the original $total string is used in the calculation. However, if it begins with anything other than a numerical representation, the value is 0. Consider another example:

<?php
$total = "1.0";
if ($total) echo "We're in positive territory!";
?>

In this example, a string is converted to Boolean type in order to evaluate the if statement. Consider one last particularly interesting example. If a string used in a mathematical calculation includes ., e, or E (representing scientific notation), it will be evaluated as a float:

<?php
$val1 = "1.2e3"; // 1,200
$val2 = 2;
echo $val1 * $val2; // outputs 2400
?>

Type-Related Functions

A few functions are available for both verifying and converting data types.
(more about functions in php)

Retrieving Types

The gettype() function returns the type of the provided variable. In total, eight possible return values are available: array, boolean, double, integer, object, resource, string, and unknown type. Its prototype follows:

string gettype(mixed var)

Converting Types

The settype() function converts a variable to the type specified by type. Seven possible type values are available: array, boolean, float, integer, null, object, and string. If the conversion is successful, TRUE is returned; otherwise, FALSE is returned. Its prototype follows:

boolean settype(mixed var, string type)


Type Identifier Functions

A number of functions are available for determining a variable’s type, including is_array(), is_bool(), is_float(), is_integer(), is_null(), is_numeric(), is_object(), is_resource(), is_scalar(), and is_string(). Because all of these functions follow the same naming convention, arguments, and return values, their introduction is consolidated into a single example. The generalized prototype follows:

boolean is_name(mixed var)


All of these functions are grouped in this section because each ultimately accomplishes the same task. Each determines whether a variable, specified by var, satisfies a particular condition specified by the function name. If var is indeed of the type tested by the function name, TRUE is returned; otherwise, FALSE is returned. An example follows:

<?php
$item = 43;
printf("The variable \$item is of type array: %d <br />", is_array($item));
printf("The variable \$item is of type integer: %d <br />", is_integer($item));
printf("The variable \$item is numeric: %d <br />", is_numeric($item));
?>

This code returns the following:

The variable $item is of type array: 0
The variable $item is of type integer: 1
The variable $item is numeric: 1

You might be wondering about the backslash preceding $item. Given the dollar sign’s special purpose of identifying a variable, there must be a way to tell the interpreter to treat it as a normal character should you want to output it to the screen. Delimiting the dollar sign with a backslash will accomplish this.


0 comments:

Post a Comment

 
Back to top!