Posts mit dem Label casting werden angezeigt. Alle Posts anzeigen
Posts mit dem Label casting werden angezeigt. Alle Posts anzeigen

Sonntag, 1. Juni 2014

PHP Basics: How can I convert from "int" to "bool", "float", "string", "array", "object"

converting variables using "int", "bool", "float", "string", "array", "object". There are several ways to cast a variable into a different variable type. This is useful in order to control what type a variable currently is. there are specific cast commands, yet you can also assign the operators in order to make sure the variable behaves as expected
$k = 4; //this will initialize the variable and set it up to be an integer
$l = (float) $k; // this converts the variable to a float
var_dump($l);

The Output is "float(4)", since the variable was converted from integer to float

Be aware that even tough integer variables can hold significant data of up to 2147483647 on a 32-Bit system, therefor they can run into overload.

PHP Basics: Converting variables integer, float, string

//type conversion: php performs automatic variable casting. make sure you get what happens behind the scenes.

$variable_g = "1"; // the result is an integer
$variable_h = "1.0"; // the result is a float

$combined_variable = $variable_g + $variable_h; // this combines the two into a new version
var_dump($combined_variable);

the output is: "float(2)", the variable was cast into a float
// then connecting two variables, in this case an integer with a float using the "." connector the result is a string

$variable_i = "1"; // the result is an integer
$variable_j = "1.0"; // the result is a float

$combined_variable = $variable_i.$variable_j; // this combines the two into a new version
var_dump($combined_variable);

the output is a "string(4) "11.0"