You don't decide the way your data is stored internallyPHP does. Behind the scenes, it supports eight internal data types (we'll see all these types in this book):
You usually don't have to worry about these data types because PHP determines a variable's type based on the kind of data you assign to it. For example, this makes $variable a string: $variable = "No worries."; This makes it a float value: $variable = 1.2345; This makes it a boolean value: $variable = TRUE; Because PHP selects the data type based on the data you assign to a variable, there's no problem here. The trouble starts when you mix data types by, for example, adding new values to the value in $variable using the + (addition) operator, which we'll see in Chapter 3. Here are some examples: <?php $variable = "0"; // $variable is a string set to "0" $variable = $variable + 2; // $variable is now an integer set to 2 $variable = $variable + 1.1; // $variable is now a float set to 3.1 $variable = 2 + "8 apples"; // $variable is now an integer set to 10 ?> If you want to avoid potential data type troubles, don't mix data types. Even if you do, PHP does the right thing almost every time (such as converting the result of adding an integer and a float into a float value, which is the right thing to do), but if you need to explicitly specify the type of a variable to PHP, you can always use a type cast. Casts appear inside parentheses and come right before the name of the variable whose type you want to specify. Here are a few examples: $int_variable = (integer) $variable; $float_variable = (float) $variable; $string_variable = (string) $variable; Some hints about mixing data types: when you're converting to the boolean type, these values are considered FALSE (more on these items, like arrays, is coming up in the book):
Every other value is considered trUE (including any resource). When you're converting to the integer type:
When you're converting to the float type, the conversion is the same as if the value was converted to an integer and then to a float. You can also convert from string to the numeric types, but that's somewhat involvedsee Chapter 3 for all the details. In the next chapter, we're going to start getting control over the data in our PHP scripts by using operators and the PHP statements that control program flow and loopingall vital items for any PHP programmer. |