PHP Type Casting: How to Convert Variables in PHP

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:

// 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:

$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.

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.

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

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:

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.

$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.

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.

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

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.

$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.

$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:

$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.

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:

$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:

$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:

$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:

$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:

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:

$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:

$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:

$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:

$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:

$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.

Similar Reads

PHP if-elseif Statement: ‘elseif’ versus ‘else if’

PHP’s if-elseif statement is a fundamental construct that allows developers to control the flow of their code based on different conditions. In…

PHP array_is_list: Check if an Array is a List with Examples

You need the array_is_list function to know if an array works as a list or not in PHP. What is…

PHP Global Variables & Superglobals: A Complete Guide

Variables in PHP are general elements used for data storage and other manipulations. Global variables belong to a particular category…

PHP array_count_values: How it Works with Examples

Developers use the array_count_values function in PHP to find how many times each value appears in an array. What is…

PHP Static Property: How It Works & Examples

PHP static property helps you manage shared data across instances, but can lead to hidden state changes. In this article,…

PHP array_merge: Combine Multiple Arrays into One

You have two or more arrays. You want one. That is the problem array_merge solves in PHP. This function lets…

Inheritance in PHP: Share Code from Class to Class & Examples

PHP developers copied and pasted code across multiple files before inheritance came, which made updates difficult. They updated functions in…

PHP Access Modifiers: How Public, Private & Protected Work

PHP supports OOP with access modifiers to prevent unintended changes and improve security. In this article, we will cover the…

PHP XML Parsers: Everything You Need to Know

In PHP, manipulation of XML data can be very critical when most systems' data exchange relies on the format. XML—Extensible…

PHP Object | How to Create an Instance of a Class

The PHP object is an instance from the PHP class or the main data structure that is already been created…

Previous Article

PHP Type Juggling: How it Works Behind the Scenes

Next Article

PHP strict_types: How the Strict Mode Works

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.