How to Change Data Type with Set Type in PHP ?

In PHP, variables are loosely typed, meaning their type can be changed dynamically. Sometimes, you need to convert a variable from one type to another to perform operations correctly. PHP provides the settype() function to explicitly change the type of a variable at runtime.


Using settype() in PHP

The settype() function changes the type of a variable to a specified data type. Its syntax is:

settype(variable, type);
  • variable – The variable whose type you want to change.
  • type – The target type ("integer", "float", "string", "boolean", "array", "object").

Examples of Changing Data Types

  1. Changing to Integer $value = "100"; settype($value, "integer"); echo $value; // Outputs: 100 echo gettype($value); // Outputs: integer
  2. Changing to Float $value = "99.99"; settype($value, "float"); echo $value; // Outputs: 99.99 echo gettype($value); // Outputs: double
  3. Changing to String $value = 123; settype($value, "string"); echo $value; // Outputs: "123" echo gettype($value); // Outputs: string
  4. Changing to Boolean $value = 0; settype($value, "boolean"); echo $value; // Outputs: (nothing, boolean false) echo gettype($value); // Outputs: boolean
  5. Changing to Array $value = "Hello"; settype($value, "array"); print_r($value); // Outputs: Array ( [0] => Hello )

Best Practices

  • Prefer type casting ((int), (string)) for simple conversions, but use settype() when you want to permanently change the variable type.
  • Always check the type after conversion using gettype() to avoid unexpected behavior.
  • Be careful with boolean conversions, as some values may evaluate to true or false in unexpected ways.

Changing a variable’s type with settype() is a powerful feature in PHP that allows you to handle data flexibly and ensure type compatibility in your applications.


External Reference: PHP Manual

View Other Articles About PHP: Learn PHP Articles

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *