Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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 143 views
1 answer 142 views
1 answer 147 views
2 answers 251 views
3 answers 232 views
...