PHP Data Type Conversion

by Vincy. Last modified on June 30th, 2022.

Datatype conversion is the process of changing the type of the variable from one datatype to another. PHP provides various datatypes and the type conversion can be performed in various methods.

Since, PHP is a loosly typed language, it allows variable declaration without specifying its datatype. The datatype of a variable will be the type of the data value initialized to it.

So, we can change the datatype of a PHP variable by changing the type of the dat initialized. The following example code will make it clear.

<?php
// $count is a string variable
$count = "5";
// $count is an int variable
$count = 5;
?>

PHP also supports explicit type casting like other programming languages. PHP type casting is similar to that of C language. PHP also provides settype() function to convert the datatype of a variable.

In this article, we are going to see type conversion examples for each data type.

PHP Typecasting for Different Datatype

The following example code shows how to do type casting in PHP to convert a variable datatype. It has a $count variable initialized with an integer value.

After initialization, I do type casting with various datatype. After each type casting, I have specified the output and the type of the variable using PHP comment line.

<?php
$count = 5;
// $count is a string; Output: "5"
$count = (string) $count;

// $count is a float; Output: 5
$count = (float) $count;

// $count is a bool; Output: true
$count = (boolean) $count;

/*
 * $count is an array
 * Output;
 * array(1) {
 * [0]=>true
 * }
 */
$count = (array) $count;

/*
 * $count is an object
 * Output;
 * (stdClass)#1 (1) {
 * [0]=>true
 * }
 */
$count = (object) $count;
?>

PHP Functions to Convert DataType

PHP provides datatype functions to get or set the datatype of a variable or to check whether a variable is a particular datatype. Those functions are gettype(), settype(), is_array(), is_null() and more.

The following code uses PHP settype() to change a variables datatype and uses gettype() and print the result to know what data type if the variable contains before and after conversion. I initialized $count variable as string convert it to an integer using PHP settype().

<?php
$count = "5";
echo gettype($count); // before datatype conversion: $count is a string
settype($count, 'int');
echo gettype($count); // after datatype conversion: $count is an integer
?>
Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “PHP Data Type Conversion”

Leave a Reply

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

↑ Back to Top

Share this page