shanti
shanti

Reputation: 81

How do I get the first and the last digit of a number in 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.

Upvotes: 7

Views: 28837

Answers (4)

FiddlingAway
FiddlingAway

Reputation: 2251

You can also use something like this (without casting).

$num = 2468;
$lastDigit = abs($num % 10); // 8

However, this solution doesn't work for decimal numbers, but if you know that you'll be working with nothing else than integers, it'll work.

The abs bit is there to cover the case of negative integers.

Upvotes: 1

Ravi Hirani
Ravi Hirani

Reputation: 6539

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

Upvotes: 18

Szymon D
Szymon D

Reputation: 441

$num = (string)123;
$first = reset($num);
$last = end($num);

Upvotes: -1

Thamilhan
Thamilhan

Reputation: 13313

You can use substr like this:

<?php

$a = 2468;
echo substr($a, 0, 1).substr($a,-1);

Upvotes: 2

Related Questions