When declaring a variable in PHP, we do not need to define the data type, and the PHP parser does that for us automatically. However, the variable's data type can be changed automatically or manually. This is referred to as typecasting.
Implicit casting is something PHP does base on your code, but you have no control over it. Dividing one integer by another integer might be either an integer or a float, and PHP makes the final choice. Take a look at the sample below.
We may cast a variable to multiple data types explicitly. For example, we may use the following formula to convert a float to an integer. (The decimal place will be removed.)
The data type you want to convert the variable to should be placed before the variable, inside parentheses.
|(int) or (integer)||To an integer, cast.|
|(float) or (double) or (real)||Toss a float in the water.|
|(bool) or (boolean)||To a boolean, cast.|
|(string)||To a string, cast.|
|(array)||To an array, cast.|
|(object)||To an item, cast.|
1. Casting to an integer The casts (int) and (integer) are both valid. When converting a float to an integer, the decimal part is removed. As a result, be certain that this decline has no further consequences.
Strings can also be turned into integers. When gathering numeric data from forms, this might be beneficial. (See the PHP forms chapter for further information.)
The following example demonstrates how casting may be used practically. Any string that begins with a number and ends with a phrase will return the beginning number as an integer when cast to an integer.
2. Casting to a float Valid casts include (float), (double), and (real). They all convert the variable to the float data type.
There will be no data loss when converting an integer to a float since integers do not contain a decimal component.
3. Casting to a boolean The terms bool and boolean are interchangeable.
4. Casting to an array Any single variable can be added to an array with only one element.