11

I was asking myself if it's possible to cast a string to become another type defined before

e.g.

$type = "int";
$foo = "5";
$bar = ($type) $foo;

and where $bar === 5

2 Answers 2

23

Yes, there's a built-in function for that:

$type = "int";
$foo = "5";
settype($foo, $type); // $foo is now the int 5

Note that the return value of settype() is the success state of the operation, and not the converted variable. Thanks to @NRVM below.

Documentation: http://php.net/manual/en/function.settype.php

Sign up to request clarification or add additional context in comments.

1 Comment

Yet you can turn a string into a boolean, so this approach is not very clean... Still looking for a way to do it with a correct error returned if casting really fails.
1

Taking the above comment, setting a variable will not return the number but a boolean for the succes state.

<?php
$type = "int";
$foo = "5";
$bar = settype($foo, $type);
var_dump($foo);
// bool(true) 
// $bar = 1

settype($foo, $type);
var_dump($foo);
// int(5)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.