The settype Function
The settype
function changes the type of a variable to the specified one. The first parameter is the variable to be converted, and the second is a string with the type name. The function returns true
on successful conversion and false
on failure.
Syntax
settype(mixed &$var, string $type): bool
Example
Convert a string to an integer:
<?php
$str = '123';
settype($str, 'integer');
var_dump($str);
?>
Code execution result:
123
Example
Convert a number to a string:
<?php
$num = 123;
settype($num, 'string');
var_dump($num);
?>
Code execution result:
'123'
Example
Try converting an array to a string:
<?php
$arr = [1, 2, 3];
$res = settype($arr, 'string');
var_dump($arr);
var_dump($res);
?>
Code execution result:
'Array'
true
Example
Convert a string to a boolean value:
<?php
$val = "true";
settype($val, "boolean");
var_dump($val);
?>
Code execution result:
true