user4802601
user4802601

Reputation:

PHP - Cast type from variable

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

Upvotes: 10

Views: 2489

Answers (2)

Joel Hinz
Joel Hinz

Reputation: 25384

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

Upvotes: 22

NVRM
NVRM

Reputation: 13067

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)

Upvotes: 1

Related Questions