用array_pad填充数组

时间:2013-11-29 14:58:57

标签: php arrays

我目前正在一个网站上工作,我有一个必须包含8个值的数组。

我生成一个随机数并将其写入我的数组中,之后我会检查这个数字是否实际为8个字符长。如果不是这种情况,则应填充前导零。

这是我正在使用的代码

$number=rand(0,255);

// convert the number to binary and store it as an array
$states=str_split(decbin($number),1);
echo '<pre>'.print_r($states,true).'</pre>';

// in case the number is not 8 bit long make it an 8 bit number using array_pad

if(count($states)<8){
   $states = array_pad($states,count($states)-8,"0");
}

现在的问题是,即使数组只包含3或4个数组,它也永远不会填满数组。

感谢您的帮助。

编辑:感谢大家的努力,Suresh Kamrushi提供的解决方案正在迅速发挥作用。

3 个答案:

答案 0 :(得分:1)

而不是

 $states = array_pad($states,count($states)-8,"0");

试试这样:

$number=rand(0,255);

// convert the number to binary and store it as an array
$states=str_split(decbin($number),1);
echo '<pre>'.print_r($states,true).'</pre>';

// in case the number is not 8 bit long make it an 8 bit number using array_pad

if(count($states)<8){
   $states = array_pad($states,8,"0");
}
print_r($states);

PHP小提琴:http://phpfiddle.org/main/code/a1d-m97

答案 1 :(得分:1)

如果我理解正确,您不需要count($states) - 8

$states = array_pad($states, -8, "0");

将数组填充为大小为8,前导零

答案 2 :(得分:1)

对于array_pad,第二个参数是您希望数组的大小,而不是您要添加到其中的项目数。

所以就这样做:

if(count($states)<8){
   $states = array_pad($states,8,"0");
}

或者,如果你的数组已经足够大,array_pad没有效果,你甚至不需要if(count($states)<8)部分。

相关问题