Comparing two numeric values has never been an issue in PHP. A comparison between two strings is also not an issue. A problem arises in non-strict comparisons between strings and numeric data (hard-coded numbers or variables containing data of the float or int type). In such cases, PHP will always convert the string to a numeric value if a non-strict comparison is executed.

The only time a string-to-numeric conversion is 100% successful is when the string only contains numbers (or numeric values such as plus, minus, or the decimal separator). We will learn how to protect against inaccurate, non-strict comparisons involving strings and numeric data. Mastering the concepts presented in this chapter is critical if we wish to produce code with consistent and predictable behavior.

Before we get into the details of string-to-numeric comparisons, we need to first gain an understanding of what is meant by a non-strict comparison.

Learning about strict and non-strict comparisons

The concept of type juggling is an essential part of the PHP language. This capability was built into the language literally from its first day. Type juggling involves performing an internal data type conversion before performing an operation. This ability is critical to the success of the language.

PHP was originally devised to perform in a web environment and needed a way to handle data transmitted as part of an HTTP packet. HTTP headers and bodies are transmitted as text and are received by PHP as strings stored in a set of super-globals, including $_SERVER, $_GET, $_POST, and so forth. Accordingly, the PHP language needs a quick way to deal with string values when performing operations that involve numbers. This is the job of the type-juggling process.

A strict comparison is one that first checks the data type. If the data types match, the comparison proceeds. Operators that invoke a strict comparison include === and !==, among others. Certain functions have the option to enforce a strict data type. One example is in_array(). If the third argument is set to TRUE, a strict-type search ensues. Here is the method signature for in_array():

Get hands-on with 1200+ tech skills courses.