Ultimate Sidebar

How to Use INT With PHP

104 1

    Data Types

    • Many programming languages -- but not PHP -- require a formal declaration of a variable before it can be used. Variables are holders for data and usually have specific properties assigned to them in a declaration, including data types. PHP gives a variable the type of the first data that is populated into it. So the variable does not have to be declared, just used consistently. For example, $a_var = “10” makes a_var a character string variable, $a_var = 10 makes it an integer variable.

    Type Casting

    • “Type casting” means converting the data in a variable from one data type to another. PHP is a very tolerant language. Many languages generate error messages or even stop running if an attempt is made to convert data to an incompatible data type. PHP does not. It just converts all it can. So, in PHP, if the string “10abc” is converted to an integer, the “abc” portion is chopped off rather than causing an error condition.

    Usage

    • The int cast preceded a variable, like a modifier. However, casts have a specific syntax that make them different from standard modifiers or functions. The intval function performs the same task as int. Whereas intval is implemented as “intval($a_var),” int is implemented as “(int) $a_val.” This differs from modifiers, which preceded the variable without brackets, like “global $var.” The int cast returns a value and so there has to be a variable set up to catch the output, or the results of the cast can be fed into another operation.

    Conditions

    • The int cast does not only convert strings into integers. A boolean variable is converted to 1 if its state is TRUE or 0 if its state is FALSE. Numbers with decimal places, stored as the floating point “float” type are rounded to the nearest whole number by int. However, int does not work well converting the output of a mathematical equation that results in fractions. In these instances it is better to perform the operation and then round the number rather than cast it as an integer.

Source: ...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.