简体   繁体   English

如何在 PHP 中获取数字的第一个和最后一个数字?

[英]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.例如 2468,我想得到数字 28。我能够得到中间的数字(46),但我不能对第一个和最后一个数字做同样的事情。

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.先感谢您。

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,最好的方法是使用Mark Ba​​ker在他的评论中描述的substr

$sum = 2468; // No need of type casting
echo substr($sum, 0, 1); // 2
echo substr($sum, -1); // 8

You can use substr like this:您可以像这样使用substr

<?php

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

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. abs位用于涵盖负整数的情况。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM