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

phpsettype(mixed &$var, string $type): bool

Example

Convert a string to an integer:

php<?php
  $str = '123';
  settype($str, 'integer');
  var_dump($str);
?>

Code execution result:

php123

Example

Convert a number to a string:

php<?php
  $num = 123;
  settype($num, 'string');
  var_dump($num);
?>

Code execution result:

php'123'

Example

Try converting an array to a string:

php<?php
  $arr = [1, 2, 3];
  $res = settype($arr, 'string');
  var_dump($arr);
  var_dump($res);
?>

Code execution result:

php'Array'
true

Example

Convert a string to a boolean value:

php<?php
  $val = "true";
  settype($val, "boolean");
  var_dump($val);
?>

Code execution result:

phptrue

See Also

  • the is_int function,
    which checks if a variable is an integer
  • the strval function,
    which converts a variable to a string
  • the intval function,
    which converts a variable to an integer