我想将这些类型的值“3”、“2.34”、“0.234343”等转换为数字。在JavaScript中,我们可以使用Number(),但在PHP中有没有类似的方法?

Input             Output
'2'               2
'2.34'            2.34
'0.3454545'       0.3454545

当前回答

使用一元运算符(+)。例如:

$n1 = +'7';
$n2 = '2.34';
$n2 = +$n1;

var_dump($n1):int(7)var_dump($n2):浮点(2.34)

其他回答

$a = "10";

$b = (int)$a;

您可以使用它在PHP中将字符串转换为int。

我发现在JavaScript中,将字符串转换为数字的简单方法是将其乘以1。它解决了连接问题,因为“+”符号在JavaScript中有多种用途,而“*”符号纯粹用于数学乘法。

基于我在这里看到的关于PHP自动愿意将包含字符串的数字解释为数字(以及关于加法的注释,因为在PHP中,“+”纯粹是用于数学加法)的内容,这种乘法技巧也适用于PHP。

我已经测试过了,它确实有效。。。尽管取决于获取字符串的方式,您可能需要在乘以1之前对其应用trim()函数。

你总是可以加零!

Input             Output
'2' + 0           2 (int)
'2.34' + 0        2.34 (float)
'0.3454545' + 0   0.3454545 (float)
//Get Only number from string
$string = "123 Hello Zahid";
$res = preg_replace("/[^0-9]/", "", $string);
echo $res."<br>";
//Result 123

您不必选择是将字符串转换为int还是float,只需在其中添加一个0,PHP就会自动将结果转换为数字类型。

// Being sure the string is actually a number
if (is_numeric($string))
    $number = $string + 0;
else // Let the number be 0 if the string is not a number
    $number = 0;