PHP 字母递增

转载请注明出处如果您觉得文章有用,就点个赞吧!

正文

我们经常会在代码中用到字母递增的问题,大多数情况下都是手动写,比如[‘A’, ‘B’, ‘C’, …, ‘AA’, ‘AB’]
在用phpxls生成文档的时候,就比较麻烦,列的变动也要跟随修改字母列

下来就用代码实现这个功能,后面就不需要变动字母列,只需关注标题列

$letter = [];
$firstLetter = 'A';

$tableHeader = ['foo','bar','',''];
$tableLen = count($tableHeader);
for ($x = 0; $x < $tableLen; $x++) {
    array_push($letter, $firstLetter++);
}
print_r($letter);
//输出如下:
// ['A', 'B', 'C', 'D']
$foo = 'Z';
echo $foo++; // AA
echo $foo++; // AB

知识扩展

在 PHP 手册 -› 运算符 -› 递增/递减运算符
中有这么一段原文:

PHP follows Perl’s convention when dealing with arithmetic operationson character variables and not C’s. For example, in PHP and Perl $a = ‘Z’; $a++; turns $a into ‘AA’, while in C a = ‘Z’; a++; turns a into ‘[’(ASCII value of ‘Z’ is 90, ASCII value of ‘[’ is 91).Note that character variables can be incremented but not decremented andeven so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported.Incrementing/decrementing other character variables has no effect, theoriginal string is unchanged.

大意是说:在处理字符变量的算数运算时,PHP 沿袭了 Perl 的习惯,而非 C 的。例如,在 Perl 中 $a = ‘Z’; $a++; 将把 $a 变成’AA’,而在 C 中,a = ‘Z’; a++; 将把 a 变成 ‘[’(‘Z’ 的 ASCII 值是 90,‘[’ 的 ASCII 值是 91)。注意字符变量只能递增,不能递减,并且只支持纯字母(a-z 和 A-Z)。递增/递减其他字符变量则无效,原字符串没有变化。

所以利用这个特性,可以在用,例如phpexcel这个plugin导出数据时,省不少事情

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值