Saruman
Saruman

Reputation: 153

PHP - Is it possible to cast to a type from a value of a string?

Like the title says, I want to cast to a type from the value of a string, for instance:

$type = "int";
$str = "20 dogs";
echo ($type)$str;

Best regards

Upvotes: 2

Views: 45

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 79024

Sure, though not in the way you are showing. There's a function for that:

settype($str, $type);
echo $str;

Also, for completeness (NOT RECOMMENDED):

eval("echo ($type)\$str;");

Upvotes: 4

Related Questions