0
0
PHPprogramming~5 mins

Settype for changing types in PHP

Choose your learning style9 modes available
Introduction

Settype changes the type of a variable to another type you want. It helps when you need a variable to be a specific type.

When you get input as a string but need it as a number to do math.
When you want to make sure a variable is a boolean true or false.
When you want to convert a number to a string to show it nicely.
When you want to reset a variable to an empty array.
When you want to force a variable to be a float for precise calculations.
Syntax
PHP
settype(variable, type);

variable is the variable you want to change.

type is a string like "int", "string", "bool", "float", or "array".

Examples
This changes the string "123" to the number 123.
PHP
$var = "123";
settype($var, "int");
echo $var;
This converts 0 to boolean false.
PHP
$flag = 0;
settype($flag, "bool");
echo $flag ? "true" : "false";
This changes the number 10 to a string "10".
PHP
$num = 10;
settype($num, "string");
echo gettype($num);
Sample Program

This program changes types of variables using settype and prints their values and types.

PHP
<?php
$val = "45.67";
settype($val, "float");
echo "Value: $val\n";
echo "Type: " . gettype($val) . "\n";

$val2 = 0;
settype($val2, "bool");
echo "Value2: " . ($val2 ? "true" : "false") . "\n";

$val3 = 5;
settype($val3, "string");
echo "Value3: $val3\n";
echo "Type3: " . gettype($val3) . "\n";
?>
OutputSuccess
Important Notes

settype changes the variable itself, no need to assign it back.

It returns true if the change worked, false otherwise.

Common types: "int", "bool", "float", "string", "array".

Summary

settype changes a variable's type directly.

Use it when you want to be sure of a variable's type.

It works with common types like int, bool, float, string, and array.