PHP type casting refers to change the variable from one data type to another data type.
This is the process of changing a variable's data type to another data type automatically or manually. This process is known as typecasting and it can be done in two ways.
Implicit data typecasting can be done by PHP automatically. Let us understand it with the help of an example. Let us perform the divide operation by two integer numbers then in this case result might be either an integer or float number.
Source Code
<?php
$x = 8;
$y = 4;
var_dump($x / $y); // 8/4 = 2 (int)
var_dump($y / $x); // 4/8 = 0.5 (float)
?>
Explicit casting can be customized by the user. Users can change variable types from one data type to another data type with the help of PHP methods.
Let us see different casting methods.
Cast | Description |
---|---|
(int) or (integer) | : Cast to an integer. |
(float) or (double) or (real) | :Cast to a float. |
(bool) or (boolean) | : Cast to a boolean. |
(string): | Cast to a string. |
(array): | Cast to an array. |
(object): | Cast to an object. |
Simply use (int)
or (integer)
to cast a variable to an integer. It can remove the decimal part from the float value and make it an integer.
Source Code
<?php
$cost = 10.75;
$collectedAmount = (int) $cost;
// cast $x to integer
var_dump($collectedAmount);
?>
String data can also be cast into integer using (int)
or (integer)
. This can be used to get numeric data from the forms
Source Code
<?php
$cost = '225';
$cost_value = (integer) $x;
// cast $cost to int
var_dump($cost_value);
?>
Casting any string that starts with a number followed by a phrase to an integer will return the starting number as an integer.
Source Code
<?php
$string = '10 Animals';
$numberOfAnimals = (int) $string;
echo $numberOfAnimals;
?>
To cast any variable into boolean use either bool
or boolean
.
Source Code
$a = (bool) 0;
$b = (bool) 5;
$c = (bool) '';
var_dump($a); // false
var_dump($b); // true
var_dump($c); // false
A single value of the variable can be cast into an array using the array()
.
Source Code
<?php
$a = (array) 5;
$b = (array) 'testing';
$c = (array) true;
var_dump($a); // [5]
var_dump($b); // ['testing']
var_dump($c); // [true]
?>
To cast a variable into float use (float)
, (double)
, and (real)
.
Source Code
<?php
$x = 7;
$y = (float) $x;
// $y is 7, but float
var_dump($y);
?>
Casting an integer into float does not lose any data loss since an integer does not have decimal points.
Type casting in PHP refers to the process of converting variables from one data type to another. PHP supports two types of casting namely implicit and explicit type casting. Implicit type casting is done by PHP automatically while explicit type casting is performed by users explicitly by the predefined methods.