PHP Type Casting

Last updated on

Type casting in PHP refers to the process of converting a variable from one data type to another. This is an imperative part of dynamic languages, such as PHP, where variables can change their types during runtime. Type casting may happen implicitly, regulated by a language's automatic type conversion mechanisms, or explicitly induced by explicit developer action.

PHP supports some data types, such as integers, floats, strings, booleans, arrays, and objects, among others. A typecast is required when there is more than one data type in an operation or comparison. PHP will automatically change the data type in most circumstances. In some cases, however, a developer may need to have control over this process and be capable of handling type changes in code accurately and predictably.

Let's briefly look at some of the capabilities of typecasting in PHP.

Understanding Automatic and Manual Variable Conversions

Implicit type casting refers to the predefined rules in PHP that automatically change the data type of variables during operations. As such, if an integer and a float are concerned with the arithmetic operation, PHP will convert the integer into a float before carrying out the arithmetic operation. While this may be very convenient, a developer should also be aware of possible pitfalls and unexpected results.

Here is a PHP code example to show how implicit typecasting works:

<?php
// Implicit type casting example
$integerVar = 5;      // Integer variable
$floatVar = 2.5;      // Float variable

$result = $integerVar + $floatVar;

// PHP will automatically convert $integerVar to float before the addition
// The result will be a float
echo "Result: " . $result;  // Output: Result: 7.5

Herein, the addition operation is between an integer-type variable $integerVar and a floating-point-type variable, $floatVar. PHP will implicitly convert it to float type before the actual addition of the two variables takes place; the result will be a float type.

On the other hand, explicit type casting is about the manual conversion of variables of one type into variables of another. PHP supports different explicit type casting operators: (int), (float), (string), (array), and (bool). In such a way, explicit type casting enables the developer to handle conversions in their preferred form.

Let me illustrate this with the following example:

Above example, explicit type casting by using the int casting operator is done, which converts the float variable $floatVar into an integer $intVar. There are various casting operators, such as int, float, string, array, and bool, that developers can use to override and handle manually.

PHP does have a pre-defined function to fetch the type of data of the value of a target variable. This is meant to be achieved using the gettype function. Let us proceed further with the next section for more information on this topic.

Explanation of "gettype" in PHP

The PHP function gettype returns the data type of a variable. It gives as output, a string showing the type of the given variable. This is quite useful when carrying out debugging or if one wants to handle different types of data dynamically inside your code. Here's a small example:

<?php 
$variable = "CodedTag PHP Tutorials";
echo gettype( $variable ); // String

Now, let's do type casting for all PHP data types by examples.

Casting Data to PHP Integer Type

You could use the (int) casting operator in PHP to cast an integer from the variable data. By this, you explicitly indicate that a variable should be treated as an integer, while it held some other type of data originally, be it string or float.

<?php 
   echo (int) "Value"; // 0
   echo (int) ""; // 0
   echo (int) null;// 0
   echo (int) 1.5; // 1
   echo (int) array(); // 0
   echo (int) array("Hello"); // 1
   echo (int) true; //1
   echo (int) false; //0
?>

But there are data types that cannot be cast to another type. For instance, an object would always fail if it's trying to cast its data to an integer. Let's take a deeper look.

<?php echo (int) new stdClass(); ?>

The above code when executed, would give an error, and the PHP interpreter lexical analysis would show an error message. Objects in PHP could not be directly cast into integers using the int-casting operator (int). If PHP scripts try to do this, it will emit an error something like:

php warning std class not found

Now, let me see what happens when I use type casting in a string data type.

Casting Data to PHP String Type

You can, in principle, convert any variable data to a string by using the (string) casting operator. This operator allows you to explicitly specify that a variable is to be treated as a string, even if it is actually an integer, a float, or even a boolean. Let's see an example.

<?php 
  $var = (string) 1;
  echo $var; // 1
  var_dump( $var ); // string(1) "1"
  echo gettype( $var ); // string
  
  echo (string) 5.6; // 5.6
  echo (string) true; // 1
  echo (string) false; // ""
?>

But in the case of an array, this will generate an error.

<?php echo (string) array(); ?>

You cannot use the same approach to cast an array or object to a string data type. If you try, you will get the following error.

Warning Class

To convert an object or array into a string, you must use the predefined PHP function serialize(). See the next example.

<?php

class Car { 
    public $peed;
}

$obj = new Car();
echo serialize($obj); 
//Output: O:3:"Car":1:{s:4:"peed";N;}

echo "\n";

echo serialize( array ( "data", 1, true, 154.56 ) );
//Output: a:4:{i:0;s:4:"data";i:1;i:1;i:2;b:1;i:3;d:154.56;}

Casting Data to PHP Boolean Type

In PHP, casting of data as a boolean type is a typical operation of conversion of a certain value to either true or false. It's an important process needed in conditional statements, logical operations, and many decision-making constructs. Casting of data as a boolean type - which includes the conversion of any data type to either true or false - is typically a common operation in PHP. This process is very important in conditional statements, logical operations, and many decision-making constructs. PHP has some rules that govern how different data types are cast to booleans.

PHP will automatically cast variable types in some contexts. For example, when it evaluates values as booleans - such as in an if statement, PHP will automatically cast values to booleans:

Let's take a look at one example.

<?php

$Value = 412; // this is an integer

if ( $Value ) {
    echo "CodedTag PHP Tutorials";
} else {
    echo "The value is falsy in a boolean context.";
}

In this example, the integer $value is used within an if statement and PHP will automatically convert it to a boolean for the purpose of the condition check. Because the value is non-zero, it is considered truthy, and hence "CodedTag PHP Tutorials." will display.

On the contrary, developers can explicitly cast values to boolean with the help of the (bool) or (boolean) casting operators.

<?php

$intValue = 42;

// Explicitly cast to boolean
$boolValue = (bool)$intValue;

Anyway, let’s plunge into how one can cast data to PHP Array Type.

Casting Data to PHP Array Type

Casting data to an array in PHP refers to the transformation of a value into an array. This is useful when you need to manipulate some non-array variable as an array or when you want to convert data into an array format. PHP explicitly allows typecasting to an array using the (array) casting operator for explicit type casting to an array.

You can explicitly cast a variable to an array using the array casting operator. Here is an example:

<?php

$scalarValue = 42;
$arrayValue = (array)$scalarValue;

// $arrayValue is now an array with a single element
print_r($arrayValue);
// Outputs: Array ( [0] => 42 )

Object to Array Conversion:

When an object is cast to an array, its properties become array elements.

<?php

class Person {
    public $name = "John";
    public $age = 30;
}

$personObject = new Person();
$personArray = (array)$personObject;

// $personArray contains the properties of the object
print_r($personArray);
// Outputs: Array ( [name] => John [age] => 30 )

String to Array Conversion:

When casting a string to an array, the text of the string becomes an element in the array:

<?php

$stringValue = "Hello";
$arrayValue = (array)$stringValue;

// $arrayValue contains each character as an element
print_r($arrayValue);
// Outputs: Array( [0] => Hello )

Associative Array to Numeric Array Conversion:

If you cast an associative array to a numeric array, PHP reindexes the array numerically:

<?php

$assocArray = ['a' => 1, 'b' => 2, 'c' => 3];
$numericArray = (array)$assocArray;

// $numericArray is reindexed numerically
print_r($numericArray);
// Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 )

Null to Empty Array:

When null is cast to an array, an empty array is created:

<?php

$nullValue = null;
$emptyArray = (array)$nullValue;

// $emptyArray is an empty array
print_r($emptyArray);
// Outputs: Array ( )

Now, let's try to understand how casting of data to PHP Object Type works.

Casting Data to PHP Object Type

In PHP, the casting of data to an object type is done with the (object) casting operator. This explicitly allows the specification that a variable should be treated as an object regardless of the data type of the variable, whether an array or scalar value.

Here’s a simple example:

<?php

$originalValue = array('key' => 'value'); // This is an array
$objectValue = (object)$originalValue; // Cast to object

// Now $objectValue is an object with- 
// properties corresponding to the array keys
echo $objectValue->key; // Output: 'value'

We can also cast strings, booleans, or integers into objects. Let’s see an example.

// Casting a string to an object
$stringValue = 'Hello, World!';
$objectFromString = (object)$stringValue;

// Casting a boolean to an object
$boolValue = true;
$objectFromBool = (object)$boolValue;

// Casting an integer to an object
$intValue = 42;
$objectFromInt = (object)$intValue;

// Displaying the properties of the resulting objects
var_dump($objectFromString);
var_dump($objectFromBool);
var_dump($objectFromInt);

So, the output generated will be in the following form:

result of var dump

Next is how casting for floats in PHP works.

Casting Data to PHP Float Type

Type casting to a float in PHP involves converting any value to a floating-point number. This is quite useful when you have to ensure that a certain variable or expression is evaluated strictly as a decimal or floating-point value. PHP can cast a variable to a float type in several ways, including both implicit and explicit methods. Let's go through this process using some examples:

Implicit Casting: This is when PHP will automatically cast the type in certain circumstances. PHP will implicitly cast values to floats when necessary. For example, PHP promotes integers to floats in arithmetic operations where both types are present:

<?php

$integerValue = 42;
$floatResult = $integerValue + 3.14;

// $floatResult is a float
echo $floatResult; // Outputs: 45.14

Explicit Casting: A developer can explicitly cast values to floats using the (float) or (double) casting operators. Here’s an example:

<?php

$stringValue = "3.14";
$floatValue = (float)$stringValue;

// $floatValue is explicitly cast to a float
echo $floatValue; // Outputs: 3.14

Handling Non-Numeric Strings: If you try to convert a non-numeric string to a float, PHP will try to retrieve the number part from the start of the string. If no number can be retrieved, the outcome is 0.0:

<?php
$nonNumericString = "Hello";
$floatValue = (float)$nonNumericString;

// $floatValue is 0.0 since no numeric part is found
echo $floatValue; // Outputs: 0

Scientific Notation: Scientific notation is also supported for floats in PHP. If a numeric string contains an exponent, PHP will interpret it as a float in scientific notation:

<?php 
$scientificString = "6.022e23";
$floatValue = (float)$scientificString;

// $floatValue is cast to a float using scientific notation
echo $floatValue; // Outputs: 6.022E+23

Boolean to Float: When casting a boolean value to a float, true becomes 1.0 and false becomes 0.0:

<?php

$boolValue = true;
$floatValue = (float)$boolValue;

// $floatValue is cast to 1.0
echo $floatValue; // Outputs: 1

Wrapping Up

Type casting in PHP is a straightforward concept but one that plays an important role in reining in the inherently dynamic nature of the language's variables. Whether implicit, casting-driven automatically by type conversions; or explicit, casting-driven manually by the developer; mastering the subtleties of type conversions is integral to writing robust, error-free code.

Programmers should be aware of how PHP automatically performs type conversions in certain situations, such as when variables with different types are used in operations or comparisons. Although automatic conversion makes things easier, it is necessary to expect traps and unexpected results.

Explicit type casting provides more control for the programmers over the conversion process. PHP's casting operators, like (int), (float), (string), (array), and (bool), allow programmers to manually handle conversion according to their needs. In many scenarios, this kind of manual control becomes highly essential when precision and predictability have to be of utmost importance.

The function gettype is stored as a utility method that will be used to dynamically return what data type a variable is. This serves as a very useful debugging tool that offers a lot of flexibility in coding.

This article has discussed various areas of typecasting for the data types of PHP. Integer, Float, String, Boolean, Array, and Object. All these have shown implicit and explicit casting in each section through practical examples. Developers who deeply understand how to work with typecasting can take some burden off their shoulders that is caused by dynamic typing in PHP and write code, which would be efficient and resistant to unexpected scenarios while working with data types.

Frequently Asked Questions (FAQs)

  • What is type casting in PHP?

    Type casting in PHP is just a way of changing a variable from one type to another. So, if you’ve got a string (text) and need it to act like a number, you can use type casting to make it happen. This can be super helpful when PHP needs to work with different types of data, like adding numbers or showing text, without running into errors.
  • Why would I need type casting in PHP?

    You need type casting when you’ve got different types of data that have to work together, like a number and a string, for example. PHP can sometimes switch types automatically, but when you need more control—like making sure a number from a form actually works as a number for calculations—type casting helps. It keeps your code running smoothly, preventing those annoying errors that pop up when types don’t match.
  • How does PHP handle type casting automatically (implicit casting)?

    PHP will automatically change types for you in certain situations. For example, if you try to add a whole number (integer) to a decimal number (float), PHP will automatically treat the integer as a float to make the addition work. It’s kind of like PHP guessing what you want it to do based on what’s already in the code. Handy, right? Here is example:
    <?php
    $integer = 5; 
    $float = 2.5; 
    
    $result = $integer + $float;  
    echo "Result: " . $result;  // Outputs: Result: 7.5
    ?>
    Here, PHP adds the integer and float by converting $integer to a float to make the addition smooth.
  • How can I cast a variable in PHP manually (explicit casting)?

    To cast a variable explicitly (manually), you can use casting operators like (int) for integers, (float) for decimals, (string) for text, (array) for lists, or (bool) for true/false values. Here’s how it looks in PHP:
    <?php
    $number = (int)"5.9";  
    echo $number;  // Outputs: 5
    ?>
    Here, I’m telling PHP, "Hey, treat this text as a number." PHP then takes the string "5.9" and turns it into 5, dropping the decimal.
  • What’s the difference between implicit and explicit type casting?

    Implicit casting is when PHP does the type-switching for you, like automatically treating a number as a string if needed. Explicit casting is when you do it yourself by using (int), (float), (string), etc., before a variable. So, you’re telling PHP exactly how to treat the data. Think of it as a helpful hint to PHP that you want it to see things a certain way.
  • How do I convert a string to an integer in PHP?

    If you’ve got a string that looks like a number and you want it as an integer, just put (int) before the variable. This makes PHP treat the text like a number. Here’s an example:
    <?php
    $intVar = (int)"123";  
    echo $intVar;  // Outputs: 123
    ?>
    So if you try to convert "123", PHP sees it as 123—an integer you can use in calculations.
  • Can I turn a boolean into a string in PHP?

    Yes, you can! You just use (string) in front of the boolean variable. Here’s what it looks like:
    <?php
    $boolean = true;
    $string = (string)$boolean;  
    echo $string;  // Outputs: 1
    ?>
    If true, it becomes "1", and if false, it becomes an empty string "". This can be handy if you need to store or display a boolean as text.
  • What are some common type casting operators in PHP?

    The most common casting operators you’ll use are: - (int) for integers - (float) for decimal numbers - (string) for text - (array) for lists of data - (bool) for true/false values Each one changes the variable to that specific type, giving you more control over how PHP works with your data.
  • What happens if I try to turn an array into a string in PHP?

    PHP doesn’t let you cast an array directly to a string; it’ll throw an error. If you really need to represent an array as text, you can use serialize() to make it into a string. Here’s how:
    <?php
    $array = ["apple", "banana", "cherry"];
    $serialized = serialize($array);
    echo $serialized;  
    ?>
    Using serialize() turns the array into a string format, which you can then save or send as text.
  • How do I change an object to an array in PHP?

    If you need to turn an object into an array, put (array) in front of the object. Here’s what that looks like:
    <?php
    class Car {
        public $color = "blue";
        public $model = "Toyota";
    }
    
    $carObject = new Car();
    $carArray = (array)$carObject;
    print_r($carArray);  
    ?>
    This takes the object’s properties and places them in an array format, making it easy to access each part as array elements.
  • What happens if I cast null to an array in PHP?

    When you cast null to an array, PHP will treat it as an empty array. This can be useful for setting up empty arrays without errors:
    <?php
    $nullValue = null;
    $array = (array)$nullValue;
    print_r($array);  
    ?>
    Here, null becomes an empty array, which you can then add data to without issues.
  • How can I check the type of a variable in PHP?

    Use gettype() to find out what type a variable is. This function gives you a string saying whether it’s a string, integer, array, object, and so on:
    <?php
    $variable = "Hello, world!";
    echo gettype($variable);  // Outputs: string
    ?>
    It’s helpful when you’re debugging or need to verify that you’re working with the type you expect.
  • Can type casting in PHP lead to unexpected results?

    Yes, sometimes type casting gives unexpected results. For example, if you cast a non-numeric string like "hello" to an integer, PHP will return 0. Implicit casting (where PHP guesses the type) can also sometimes give results that aren’t exactly what you expect, so it’s smart to be cautious with type casting.
  • What happens if I try to cast an object to an integer in PHP?

    PHP doesn’t allow direct casting of objects to integers, so you’ll get an error if you try:
    <?php
    $object = new stdClass();
    $int = (int)$object;  
    ?>
    Objects just aren’t meant to be treated as numbers, so PHP won’t let you make this kind of conversion.
  • How does PHP handle true/false (boolean) type casting?

    PHP has certain rules for turning values into booleans: - Values like 0, "0", empty strings, empty arrays [], and null become false. - Everything else, like non-zero numbers and non-empty strings, is treated as true. This conversion usually happens automatically in conditions like if statements, but you can force it by adding (bool) before the variable.
  • How do I cast a decimal (float) to an integer in PHP?

    To change a float to an integer, use (int) in front of it:
    <?php
    $floatValue = 5.75;
    $intValue = (int)$floatValue;  
    ?>
    PHP will drop the decimal part, turning 5.75 into 5. So, keep in mind that it won’t round up or down, just chops off the decimal.
  • What does type juggling mean in PHP?

    Type juggling is when PHP automatically changes the type of a variable based on the context. For instance, if you add a string like "10" to an integer, PHP will treat the string like a number to make the addition work. Type juggling is helpful but can sometimes lead to confusion if you’re not expecting it.
  • How does PHP handle scientific notation in type casting?

    PHP understands scientific notation when casting to floats. So if you cast a string in scientific notation to a float, PHP will interpret it as a decimal:
    <?php
    $scientificString = "1.23e3";
    $floatValue = (float)$scientificString;  
    ?>
    Here, PHP reads "1.23e3" as 1230, which can be useful for really large or really small numbers.
  • Why does PHP sometimes return 0 when casting?

    PHP will return 0 if you try casting a non-numeric string to an integer or float. If there’s no number in the string, PHP just gives you 0 because there’s nothing to convert.
    <?php
    $nonNumeric = "hello";
    $number = (int)$nonNumeric;  
    ?>
  • What is serialize() used for in PHP?

    serialize() is a PHP function that turns complex data, like arrays or objects, into strings. This is useful when you want to store the data as text or send it over a network:
    <?php
    $array = ["apple", "banana", "cherry"];
    $serialized = serialize($array);
    echo $serialized;  
    ?>
    You can later use unserialize() to bring the data back to its original form.
Share on: