While performing any operation PHP will try to cast variables to the appropriate data type as per the operation requirement. But sometimes we need to do it explicitly.
Let’s see how we can cast/convert one data type to another data type in PHP. We can as one data type to another using one of the following-
- Casting operator
- Functions for casting
Convert to Type | Casting Operator | Casting Function |
---|---|---|
boolean | (bool) | boolval() |
Integer | (int) | intval() |
Float | (float) | floatval() |
String | (string) | strval() |
Array | (array) | |
Object | (object) |
<?php
$bigBoxVal = "99";
$intValue = (int) $bigBoxVal;
var_dump($intValue);
$bigBoxVal = 1;
$boolValue = (bool) $bigBoxVal;
var_dump($boolValue);
$bigBoxVal = "3.1416";
$floatValue = (float) $bigBoxVal;
var_dump($floatValue);
$bigBoxVal = 123;
$stringValue = (string) $bigBoxVal;
var_dump($stringValue);
$bigBoxVal = "BigBoxCode";
$arrayValue = (array) $bigBoxVal;
print_r($arrayValue);
$bigBoxVal = ['name' => 'BigBoxCode'];
$objectValue = (object) $bigBoxVal;
var_dump($objectValue);
PHPOutput:
int(99)
bool(true)
float(3.1416)
string(3) "123"
Array
(
[0] => BigBoxCode
)
object(stdClass)#1 (1) {
["name"]=>
string(10) "BigBoxCode"
}
Plaintext