How to get the first and the last digit of a number in PHP

5 Answers

0 votes
$n = 234728;

$first_digit = substr($n, 0, 1);
echo $first_digit ."\n";

$last_digit = $n % 10;
echo $last_digit;





/*
run:

2
8

*/

 



answered Jun 2, 2020 by avibootz
0 votes
$n = 234728;

$s = (string)$n; 

echo $s[0] . "\n";
echo $s[strlen($s) - 1];





/*
run:

2
8

*/

 



answered Jun 2, 2020 by avibootz
0 votes
$n = 234728;

echo substr($n, 0, 1) . "\n";
echo substr($n, -1); 





/*
run:

2
8

*/

 



answered Jun 2, 2020 by avibootz
0 votes
$n = 234728;

$arr = str_split($n); 
echo reset($arr) . "\n";
echo end($arr);  





/*
run:

2
8

*/

 



answered Jun 2, 2020 by avibootz
0 votes
$n = 234728;

$arr = str_split($n); 
echo $arr[0] . "\n";
echo $arr[sizeof($arr) - 1];  





/*
run:

2
8

*/

 



answered Jun 2, 2020 by avibootz

Related questions

1 answer 156 views
1 answer 154 views
1 answer 160 views
2 answers 262 views
3 answers 250 views
...