0

I am currently working on a site where I have an array that must contain 8 values.

I generate a random number and write it into my array, after that i would liek to check if this number was infact 8 character long. If this was not the case it should be filled with leading zero's.

Here is the code i am using

$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");
}

The problem is now that it never fills up the array even if the array only consists of 3 or 4 entrys.

Thanks for the help.

Edit :Thanks to everyone for awnsering so quickly the solution provided by Suresh Kamrushi is working.

3 Answers 3

1

instead of

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

Try like this:

$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 fiddle: http://phpfiddle.org/main/code/a1d-m97

Sign up to request clarification or add additional context in comments.

Comments

1

If I understand correctly you don't need count($states) - 8:

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

Which will pad the array to a size of 8, with leading zeroes

Comments

1

For array_pad the second argument is the size you want the array to be, not the number of items you want to add to it.

So just do:

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

Or, as array_pad has no effect if your array is already big enough, you don't even need the if(count($states)<8) part.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.