1 3 Votes

PHP: Get first Digit of Number or String

Tutorial by Anja Proggy | 10/03/2014 at 17:14

Question: I have some numbers and strings and I would like to determine their first digit using PHP. Have someone an idea of how to do that?


If you have a string, you can treat it just like an array to get its first character:

$s = '123';
$a = $s[0];  
echo $a; // 1

So, you can just use the square brackets. The first place is the 0, the second the 1 and so on.


However, if You should have a number variable, you can not use the square brackets. Spontaneously, I have three possibilities in mind of how to proceed in this case:

// Possibility 1
$k = 123;
$s = $k.''; // or: $s = (string)$k;
$a = $s[0];  
echo $a; // 1

// Possibility 2
$k = 123;
$a = floor($k/100);
echo $a; // 1

// Possibility 3
$k = 123;
$a = substr($k, 0, 1); 
echo $a; // 1

The first possibility is to convert the number into a string type to be able to proceed like in the case of a string. You can do this conversion for example by simply attaching an empty string or by using a type cast by writing (string) in front of the variable (more about type conversions).

In the second way, the variable remains a number. We just divide the 123 by 100 so that we get the floating number 1.23. After that, we are cutting off the digits behind the decimal point using floor(). Of course, this procedure implies that we now the number of digits of the number or that they have to determine those number before. Accordingly, when having two-digit numbers we have to divide by 10, when having four-digit numbers by 1000.

The third and last possibility I would like to introduce is to work with substr(). This is a PHP function that can return parts of a string. The first parameter that is passed is the variable that should be cut. The second is the starting point and the third parameter is the lenght. In our example, we can directly pass the number as variabl because substr() is caring about the type casting automatically. Because we are interested in the first digit, we are starting with 0 and we are using the length of 1 to get the first character.


About the Author

Show Profile | Message


Related Topics

PHP: Rounding Numbers
Tutorial | 0 Comments

Important Note


