Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/239.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 浇注式效率_Php_Casting - Fatal编程技术网

Php 浇注式效率

Php 浇注式效率,php,casting,Php,Casting,我已经想了好几天了,有时我发现自己不得不使用PHP可用的类型转换方法: 并开始研究效率/正确的方法。。要展示我脑海中的类似场景,应该是: /* The benchmark test: Expected Output: string Actual Output: string */ $Percentile = "20%"; echo gettype($Percentile); ?> <br><br&g

我已经想了好几天了,有时我发现自己不得不使用PHP可用的类型转换方法:

并开始研究效率/正确的方法。。要展示我脑海中的类似场景,应该是:

/*
    The benchmark test: 
        Expected Output: string
            Actual Output: string 
*/
$Percentile = "20%";
echo gettype($Percentile); 
?>
<br><br>
Force Casting to an Integer: 
<br><br>
<?php
    /*
        Remove the %age from the string before force re-cast
            Expected Output: integer 
            Actual Output: integer 
                Test Passed 
    */
    unset($Percentile); // Just to reduce any cached validations 
    $Percentile = "20%";
    $Percentile = (int)$Percentile;
    echo $Percentile."\r\n";
    echo gettype($Percentile);
?>
<br><br>
Str Replace to remove the '%' and cast to integer
<br><br>
<?php 
    /*
        Remove the %age from the string before force re-cast
            Expected Output: integer 
            Actual Output: integer 
                Test Passed 
    */
    unset($Percentile);
    $Percentile = "20%";
    $Percentile_New = str_replace("%","",$Percentile);
    echo $Percentile_New."\r\n"; // 
    echo gettype((int)$Percentile_New);
?>
返回错误:

分析错误:语法错误,意外“;”

因此,创建百分比将使用字符串转换表示法创建,但这不是问题的主要目的

总的问题是哪种方式更有效

方法1:

强制强制转换类型为整数,但不删除%age

方法2:

使用
str\u replace
然后在删除%age后强制强制转换类型为整数


效率是减少错误数据转换类型的空间(如果可能发生这种问题)

鉴于该示例,不执行任何字符串操作,而是直接使用类型转换显然更有效。给定字符串的结果是相同的。

$Percentile=0.2绝对应该是最有效的赋值方法。您似乎使用了一个奇怪的“高效”定义。这通常指运行速度更快或占用内存更少的coade。@Barmar True,让我们用效率代替可靠性您可能不应该依赖随机格式的自动转换。如果事先知道百分比字符串以
%
结尾,请使用
substr
将其删除。
$Percentile = 20%;