0
0
PHPprogramming~10 mins

Settype for changing types in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Settype for changing types
Start with variable
Call settype(var, type)
Change variable type
Variable now has new type and value
Use variable with new type
The flow shows how settype changes a variable's type and value, then you use the variable with its new type.
Execution Sample
PHP
<?php
$var = "123";
settype($var, "int");
echo gettype($var) . ": " . $var;
?>
This code changes a string variable to an integer and prints its type and value.
Execution Table
StepVariableOriginal TypeActionNew TypeNew ValueOutput
1$varstringInitialize with "123"string"123"
2$varstringsettype($var, "int")integer123
3$varintegerecho gettype($var) . ": " . $varinteger123integer: 123
4-----Execution ends
💡 After step 3, the variable is an integer with value 123, so execution ends.
Variable Tracker
VariableStartAfter settypeFinal
$var"123" (string)123 (integer)123 (integer)
Key Moments - 3 Insights
Why does the variable value change when we use settype?
Because settype converts the variable to the new type, PHP changes the value to match that type, as shown in step 2 of the execution_table.
Does settype return the new value or the variable itself?
settype returns a boolean true on success, but the variable itself is changed by reference, as seen in step 2 where $var changes type and value.
What happens if you settype to 'bool' with a non-empty string?
PHP converts any non-empty string to true (boolean), so the variable becomes true, similar to how it changed to integer in the example.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the type of $var after step 2?
Ainteger
Bstring
Cboolean
Dfloat
💡 Hint
Check the 'New Type' column in step 2 of the execution_table.
At which step does the output 'integer: 123' appear?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Output' column in the execution_table.
If we change settype($var, "int") to settype($var, "bool"), what would be the new value of $var after step 2?
Afalse
Btrue
C0
D"bool"
💡 Hint
Recall that any non-empty string converts to true when cast to boolean in PHP.
Concept Snapshot
settype(variable, type) changes the variable's type in place.
Supported types: 'int', 'integer', 'bool', 'boolean', 'float', 'string', etc.
The variable's value changes to match the new type.
settype returns true on success.
Use gettype() to check the variable's type after conversion.
Full Transcript
This example shows how PHP's settype function changes a variable's type and value. Initially, $var is a string with value "123". After calling settype($var, "int"), $var becomes an integer with value 123. When we print the type and value, it outputs 'integer: 123'. The variable changes by reference, and settype returns true. This helps convert variables to needed types easily.