简体   繁体   中英

If statement based on last digit of php variable number

Given we have different variables looking like this: "345321", "5" or "42"

How can we test the last number of these strings in a if statement?

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 :-)

This is the documentation of phps first grade mathematical operators. Modulo is mentioned last: 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()

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

$var = 1234154;

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

/* will output
It's four
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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