Number comparisons in PHP 8

PHPServer Side ProgrammingProgramming

When we compare a numeric in PHP 8, it will use number comparison. Else it will convert the number to a string and will use the string comparison.

The string can be categorized in three ways −

  • A string that contains only numeric. Example − 1234 or 1.24e1.

  • A leading–numeric string − A leading string starts with a numeric string but it should be followed with non-numeric characters including the white space. Example − 12xyz or “123”

  • Non-numeric string − The string which cannot be numeric and also a non-leading numeric string.

Example − PHP 7
0=='foo' // PHP 7 will return true.
Example − PHP 8
0 =='foo' // PHP 8 will return false.

Example − PHP 8 program using Saner string to number comparisons.

 Live Demo

<?php
   $x=[
      "1" => "first Integer",
      "0123" =>"The integer index with leading 0",
      "12str" =>"using leading numeric string",
      " 1" => "using leading whitespace",
      "2.2" => "using floating number",
   ];
   print_r($x);
?>

Output

Array
(
   [1] => first Integer
   [0123] => The integer index with leading 0
   [12str] => using leading numeric string
   [ 1] => using leading whitespace
   [2.2] => using floating number
)
raja
Published on 01-Apr-2021 06:18:35
Advertisements