Heim > Artikel > Backend-Entwicklung > 如何正确实现PHP字符串转换为数值的需求_PHP教程
当一个字符串被当作数字来求值时,根据以下规则来决定结果的类型和值。
如果包括“.”,“e”或“E”其中任何一个字符的话,字符串被当作 float 来求值。否则就被当作整数。
该值由字符串最前面的部分决定。飞飞,Asp技术乐园如果字符串以合法的数字数据开始,就用该数字作为其值,否则其值为 0(零)。合法数字数据由可选的正负号开始,后面跟着一个或多个数字(可选地包括十进制分数),后面跟着可选的指数。飞飞Asp!技术乐园指数是一个“e”或者“E”后面跟着一个或多个数字。
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><span> ?php </span></span></span></li> <li> <span>$</span><span class="attribute">foo</span><span> = </span><span class="attribute-value">1</span><span> + "10.5"; <br>// $foo is float (11.5) </span> </li> <li class="alt"> <span>$</span><span class="attribute">foo</span><span> = </span><span class="attribute-value">1</span><span> + "-1.3e3"; <br>// $foo is float (-1299) </span> </li> <li> <span>$</span><span class="attribute">foo</span><span> = </span><span class="attribute-value">1</span><span> + "bob-1.3e3"; <br>// $foo is integer (1) </span> </li> <li class="alt"> <span>$</span><span class="attribute">foo</span><span> = </span><span class="attribute-value">1</span><span> + "bob3"; <br>// $foo is integer (1) </span> </li> <li> <span>$</span><span class="attribute">foo</span><span> = </span><span class="attribute-value">1</span><span> + "10 Small Pigs"; <br>// $foo is integer (11) </span> </li> <li class="alt"> <span>$</span><span class="attribute">foo</span><span> = </span><span class="attribute-value">4</span><span> + "10.2 Little Piggies";<br> // $foo is float (14.2) </span> </li> <li> <span>$</span><span class="attribute">foo</span><span> = </span><span class="attribute-value">"10.0 pigs "</span><span> + 1; <br>// $foo is float (11) </span> </li> <li class="alt"> <span>$</span><span class="attribute">foo</span><span> = </span><span class="attribute-value">"10.0 pigs "</span><span> + 1.0; <br>// $foo is float (11) </span> </li> <li> <span class="tag">?></span><span> </span> </li> </ol>
如果想测试本节中的任何PHP字符串转换为数值的例子,可以拷贝和粘贴这些例子并且加上下面这一行自己看看会发生什么
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><span> ?php </span></span></span></li> <li> <span>echo "$</span><span class="attribute">foo</span><span>==$foo; type is " .<br> gettype ($foo) . "</span><span class="tag"><span> </span><span class="tag-name">br</span><span> </span><span class="tag">/></span><span>n"; </span></span> </li> <li class="alt"> <span class="tag">?></span><span> </span> </li> </ol>
不要指望在将一个字符转换成整型时能够得到该字符的编码(可能也会在 C 中这么做)。如果希望在字符编码和字符之间实现PHP字符串转换为数值,请使用 ord() 和 chr() 函数。