Page 1 of 1

[SOLVED] How to replicate VB right()?

Posted: Mon Jan 05, 2004 9:15 am
by ade
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

Posted: Mon Jan 05, 2004 9:28 am
by redmonkey
Have a look at substr()

Code: Select all

<?php

$value = 36;

$newvalue = substr($value, -1);

echo $newvalue;
?>

Posted: Mon Jan 05, 2004 10:00 am
by jollyjumper
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 :D

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));
}

?>
Greetz Jolly.

Posted: Mon Jan 05, 2004 10:08 am
by ade
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.

Code: Select all

<?php 

$DecimalPlace = $IntNumber / 10;
$BigString = strval($DecimalPlace);
$SmallStringArray = explode(".",$BigString);
$ProdCalcNum = $SmallStringArray[1];

?>
Your way is much neater though.

ade
uk

Posted: Mon Jan 05, 2004 10:32 am
by m3mn0n
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.

Code: Select all

<?php
$value = (int) 36;
$newvalue = substr($value, -1); 
echo "Result: ".$newvalue."<br>";
echo "Type: ".gettype($newvalue);
?>
Output:
Result: 6
Type: string
Here is the simple fix:

Code: Select all

<?php
$value = (int) 36;
$newvalue = substr($value, -1); 
$newvalue = (int) $newvalue; // new line
echo "Result: ".$newvalue."<br>";
echo "Type: ".gettype($newvalue);
?>
Output:
Result: 6
Type: integer
Reference material:
http://www.php.net/manual/en/language.t ... er.casting