drl971115 2014-05-05 13:08
浏览 15
已采纳

未初始化的字符串偏移错误处理

I have a variable name $accountNumber which holds a 9 digit number. When a user types it in and when it is displayed, it is cut up in 9 separate box's.

Like so: how the account number is displayed

When getting the account number I do something like this:

//$data['acountNumber'] = 453554334;

$accountNumber = (string)$data['accountNumber'];
$accountNumber_0 = $accountNumber[0];
$accountNumber_1 = $accountNumber[1];
$accountNumber_2 = $accountNumber[2];
$accountNumber_3 = $accountNumber[3];
$accountNumber_4 = $accountNumber[4];
$accountNumber_5 = $accountNumber[5];
$accountNumber_6 = $accountNumber[6];
$accountNumber_7 = $accountNumber[7];
$accountNumber_8 = $accountNumber[8];

However, if I don't have an account number listed, I get an Uninitialized string offset error. I can make this "go away" if I add an @ in font of each $accountNumber[#] but I thought I would ask you guys if there is a better way at handling this.

What do you think?

EDIT - After accepted answer

The below answers work great. But since I needed to have my array be size 9 no matter what, I found that this works best.

$accountNumber = array_pad(str_split($data['accountNumber']), 9, '');

  • 写回答

2条回答 默认 最新

  • douba1214 2014-05-05 13:17
    关注

    You have not converted the string to array. str_split would do that for you.

    This should work for you:

    <?php
    
    $data['acountNumber'] = 453554334;
    $data['acountNumber'] = strval($data['acountNumber']); // converts numbers to string
    
    $accountNumber = str_split($data['acountNumber']); // split the string to array
    $accountNumber_0 = $accountNumber[0];
    $accountNumber_1 = $accountNumber[1];
    $accountNumber_2 = $accountNumber[2];
    $accountNumber_3 = $accountNumber[3];
    $accountNumber_4 = $accountNumber[4];
    $accountNumber_5 = $accountNumber[5];
    $accountNumber_6 = $accountNumber[6];
    $accountNumber_7 = $accountNumber[7];
    $accountNumber_8 = $accountNumber[8];
    

    Here is a PHP Fiddle that shows it in action.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?