假设我们有不同的变量,如下所示:"345321"、"5"或"42"
我们如何在if语句中测试这些字符串的最后一个数字?
if ( $variable == 1 ) {
echo 'its one';
} elseif ($variable == 2 || $variable == 3) {
echo 'its two or three';
}
看看"模"运算:
<?php
$value = 35482;
echo $value%10;
输出为:2
:-)
这是php一级数学运算符的文档。Modulo最后提到:http://php.net/manual/en/language.operators.arithmetic.php
有多种解决方案:
1. substr($var, -1) ; // Use substr() with a negative number for the 2nd argument, It will work for all string and digits
2. $var % 10; //work only for numbers
参考:substr()
您可以使用模运算符和NumberFormatter
类来完成此操作
$var = 1234154;
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo "It's " . $f->format($var%10);
/* will output
It's four
*/
试试这个:
$variable = '223265659';
$digitArr = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
echo "its ". $digitArr[$variable%10];