简体   繁体   English

if语句基于php变量号的最后一位

[英]If statement based on last digit of php variable number

Given we have different variables looking like this: "345321", "5" or "42" 假设我们有如下所示的不同变量:“ 345321”,“ 5”或“ 42”

How can we test the last number of these strings in a if statement? 我们如何在if语句中测试这些字符串的最后数目?

if ( $variable == 1 ) {

    echo 'its one';

} elseif ($variable == 2 || $variable == 3) {

    echo 'its two or three';
}

Take a look at the "modulo" operation: 看一下“取模”操作:

<?php
$value = 35482;
echo $value%10;

The output is: 2 :-) 输出为: 2 :-)

This is the documentation of phps first grade mathematical operators. 这是phps一级数学运算符的文档。 Modulo is mentioned last: http://php.net/manual/en/language.operators.arithmetic.php 最后提到了Modulo: http//php.net/manual/en/language.operators.arithmetic.php

There are multiple solutions: 有多种解决方案:

 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

Reference : substr() 参考: substr()

Try this: 尝试这个:

$variable = '223265659';
$digitArr = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
echo "its ". $digitArr[$variable%10];

You can do this with the modulo operator and the NumberFormatter class 您可以使用模运算符和NumberFormatter类来完成此操作

$var = 1234154;

$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo "It's " . $f->format($var%10);

/* will output
It's four
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM