鉴于我们有不同的变量,如下所示:“345321”,“5”或“42”
我们如何在if语句中测试这些字符串的最后一个数字?
if ( $variable == 1 ) {
echo 'its one';
} elseif ($variable == 2 || $variable == 3) {
echo 'its two or three';
}
答案 0 :(得分:4)
看看" modulo"操作:
<?php
$value = 35482;
echo $value%10;
输出为:2
: - )
这是phps一年级数学运算符的文档。最后提到了Modulo:http://php.net/manual/en/language.operators.arithmetic.php
答案 1 :(得分:2)
有多种解决方案:
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()
答案 2 :(得分:0)
试试这个:
$variable = '223265659';
$digitArr = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
echo "its ". $digitArr[$variable%10];
答案 3 :(得分:0)
您可以使用模运算符和NumberFormatter
类
$var = 1234154;
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo "It's " . $f->format($var%10);
/* will output
It's four
*/