Hi,
I need to extract the rightmost digit from an integer variable eg. if the variable value is 36, I need to return 6.
In VB, the function right() will do this for me. I cannot find a function in php to achieve this.
Can anybody help me?
Thanks in advance
ade
uk
[SOLVED] How to replicate VB right()?
Moderator: General Moderators
Have a look at substr()
Code: Select all
<?php
$value = 36;
$newvalue = substr($value, -1);
echo $newvalue;
?>-
jollyjumper
- Forum Contributor
- Posts: 107
- Joined: Sat Jan 25, 2003 11:03 am
Hi Ade,
Below are two functions I've written when I had to learn php after only have worked with VB. I still use them today
Greetz Jolly.
Below are two functions I've written when I had to learn php after only have worked with VB. I still use them today
Code: Select all
<?php
function left($string, $length) {
return substr($string,0,$length);
}
function right($string, $length) {
return substr($string,strlen($string)-$length,strlen($string));
}
?>Excellent, thank you.
I did find a workaround dividing my integer by 10 to get a decimal point. This was then used as the separator in an explode() and I took the array element as my rightmost digit.
Your way is much neater though.
ade
uk
I did find a workaround dividing my integer by 10 to get a decimal point. This was then used as the separator in an explode() and I took the array element as my rightmost digit.
Code: Select all
<?php
$DecimalPlace = $IntNumber / 10;
$BigString = strval($DecimalPlace);
$SmallStringArray = explode(".",$BigString);
$ProdCalcNum = $SmallStringArray[1];
?>ade
uk
To be proper, and if the type of variable is of any importance, you should convert the output back into integer format since the [php_man]substr[/php_man]() func would return a string.
Eg.
Output:
Output:
http://www.php.net/manual/en/language.t ... er.casting
Eg.
Code: Select all
<?php
$value = (int) 36;
$newvalue = substr($value, -1);
echo "Result: ".$newvalue."<br>";
echo "Type: ".gettype($newvalue);
?>Here is the simple fix:Result: 6
Type: string
Code: Select all
<?php
$value = (int) 36;
$newvalue = substr($value, -1);
$newvalue = (int) $newvalue; // new line
echo "Result: ".$newvalue."<br>";
echo "Type: ".gettype($newvalue);
?>Reference material:Result: 6
Type: integer
http://www.php.net/manual/en/language.t ... er.casting