23 of 410 menu

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

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
byenru