php - 将字符串转换为 int

标签 php type-conversion

我的代码

<?php
var_dump('0xD' * 1 );
var_dump((int)'0xD');
var_dump(intval('0xD'));
var_dump((float)'0xD');

实际结果:

int(13)
int(0)
int(0)
float(0)

为什么前两个条件的结果不一样?你能给我提供正确的文件吗?

我只找到了

  • Type Casting : PHP 中的类型转换与在 C 中的工作方式非常相似:所需类型的名称写在要转换的变量之前的括号中。在某些类型之间转换时究竟会发生什么可能并不明显。有关详细信息,请参阅以下部分:...
  • Converting to integer :来自字符串: 查看字符串到数字的转换
  • String conversion to numbers当在数字上下文中评估字符串时,结果值和类型确定如下。

所以,据我所知,文档说直接转换为 int 和通过放入数字上下文应该是相同的。我的错误是什么?

已添加:在回答之前尝试检查第一个和第二个代码(和输出)。

最佳答案

'0xD'是一个字符串。 documentation clearly specifies如何将字符串“转换”为整数值(此处选择 (int) '0xD'; 示例):

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

字符串的初始部分'0xD'那是一个数字是0 ,因此它是 (int) 0 .

不要将此与编写代码混为一谈。如果你在代码中写它不是字符串,它是整数的十六进制表示/符号 ( Demo ):

<?php

$value = eval("return 0xD;");

var_dump($value); # int(13)

这并没有完全回答为什么表达式 '0xD' * 1结果 (int) 13 , 但解释了到目前为止的所有其他内容以及整数值解释的哪两条规则适用于 PHP。

我假设在 PHP 中转换为整数和整数上下文之间存在细微差别。如果表示十六进制数的字符串用于整数/ float 上下文中:

'0xD' * 1

在此表达式中,字符串 '0xD'由于 * 将被评估为数字运算符和 1操作数(参见 Type Juggling )。这不是类型转换,因为没有转换语言结构。

看起来在这个表达式的情况下,将字符串解释为整数 is done literally (如指定的那样)但与进行转换时不同。

有人可能会争辩说,当应用转换和字面解释时,它仍然没有记录。但是,使用类型转换可以解决任何此类问题(Demo):

<?php

$value = '0xD';

var_dump($value); # string(3) "0xD"
var_dump($value * 1); # int(13)
var_dump((int) $value * 1); # int(0)

关于php - 将字符串转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6967375/

相关文章:

c# - 在 C# 中使用 fo-dicom 操作和转换 CT 图像的像素数据

php - 如何通过单个 PHP 和 MySql 查询将数据保存在多个连续文件中以生成产品数据源

javascript - jQuery TableSorter 在 <td> 使用 Ajax 更新数据库更新后不排序?

php - 使用 DateInterval 计算两个日期之间的月份,而不在一年内换行

php - HTML 表单 POST $_REQUEST 数据消失

c - 如何在c程序中将u-law和a-law编码的wav文件转换为pcm wav文件?

java - JLayeredPane z 顺序问题

python - 从字符串和列表的元组中以字符串形式返回所有值

javascript - 从数组值中获取值以形成聊天

c++ - 尝试舍入数字时如何避免精度损失? (C++)