Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the first and the last digit of a number in PHP?

Tags:

php

How can I get the first and the last digit of a number? For example 2468, I want to get the number 28. I am able to get the ones in the middle (46) but I can't do the same for the first and last digit.

For the digits in the middle I can do it

$substrmid = substr ($sum,1,-1); //my $sum is 2468
echo $substrmid;

Thank you in advance.

like image 874
shanti Avatar asked Dec 06 '22 18:12

shanti


1 Answers

You can get first and last character from string as below:-

$sum = (string)2468; // type casting int to string
echo $sum[0]; // 2
echo $sum[strlen($sum)-1]; // 8

OR

$arr = str_split(2468); // convert string to an array
echo reset($arr); // 2 
echo end($arr);  // 8

Best way is to use substr described by Mark Baker in his comment,

$sum = 2468; // No need of type casting
echo substr($sum, 0, 1); // 2
echo substr($sum, -1); // 8
like image 74
Ravi Avatar answered Dec 09 '22 15:12

Ravi