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

时间:2014-05-05 13:08:49

标签: php

我有一个变量名$accountNumber,它包含一个9位数字。当用户输入并显示时,它会被分成9个单独的框。

像这样: how the account number is displayed

获取帐号时,我会这样做:

//$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];

但是,如果我没有列出帐号,我会收到 未初始化的字符串偏移 错误。我可以做到这一点"走开"如果我在每个@的字体中添加$accountNumber[#],但我想我会问你们是否有更好的方法来处理它。

您怎么看?

编辑 - 接受回答后

以下答案效果很好。但是既然我需要让我的阵列大小为9,无论如何,我发现这种效果最好。

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

2 个答案:

答案 0 :(得分:4)

//Cast your string
$accountNumber = (string)$data['accountNumber'];
//Get the length of the string
$length = strlen ($accountNumber);
//Create an empty array containing the account numbers
$accountNumberArr = array();
//Start the loop
for($i = 0; $i < $length; $i++){
    //Add the account numbers to the account number array
    $accountNumberArr['accountNumber_'.$i] = $accountNumber[$i];
}

//Now you can access your account number as follows
// $accountNumberArr['accountNumber_0'], $accountNumberArr['accountNumber_1'];

答案 1 :(得分:1)

您尚未将字符串转换为数组。 str_split会为你做到这一点。

这应该适合你:

<?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];

这是PHP Fiddle,显示了它的实际效果。