PHP 8 中的数字比较

phpserver side programmingprogramming更新于 2025/8/5 4:22:17

在 PHP 8 中比较数字时,会使用数字比较。否则,它会将数字转换为字符串,然后使用字符串比较。

字符串可以分为三种类型 −

  • 仅包含数字的字符串。例如 − 1234 或 1.24e1。

  • 前导数字字符串 − 前导字符串以数字字符串开头,但后面应跟非数字字符(包括空格)。例如 − 12xyz 或 “123”

  • 非数字字符串 −不能为数字且不能为非前导数字的字符串。

PHP 7 中的示例 − 
0=='foo' // PHP 7 将返回 true。
PHP 8 中的示例 − 
0 =='foo' // PHP 8 将返回 false。

PHP 8 程序中使用更合理的字符串与数字进行比较的示例 − 。

<?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);
?>

输出

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
)

相关文章