views:

87

answers:

2

For a fun project I wanted to make a binary clock in PHP, so basically for simplicity's sake I used date("H:m:s"); to get the time in string format, then used str_split(); to separate each string letter into an array.

My code is here to work with it:

$time = str_split($time);
//I tried $time = array_map(intval, $time); here but no dice
$tarray = Array(
    //hh:mm:ss = [0][1][3][4][6][7]
    str_pad(decbin((int)$time[0]), 8, STR_PAD_LEFT), //I tried casting to (int) as well
    str_pad(decbin($time[1]), 8, STR_PAD_LEFT),
    str_pad(decbin($time[3]), 8, STR_PAD_LEFT),
    str_pad(decbin($time[4]), 8, STR_PAD_LEFT),
    str_pad(decbin($time[6]), 8, STR_PAD_LEFT),
    str_pad(decbin($time[7]), 8, STR_PAD_LEFT),
);

No matter if I try those two to fix the problem, the resulting array is for example the following (with decimal next to it for clarity):

10000000 -> 128
10000000 -> 128
10000000 -> 128
00000000 -> 0
10000000 -> 128
10010000 -> 144

Why are those not 1-9 in binary?

A: 

I am not sure but have you tried intval()?

Michael Mao
I wrote as a comment in my code originally that I used array_map with it, it does not work for some reason. I'll try one more time manually though.. EDIT: Nope, manually still doesn't touch it.
John
+3  A: 

The 4th argument of str_pad is the pad type.

You made it the 3rd argument.

3rd argument is what to use for padding which in your case is '0' so try this:

str_pad(decbin($time[1]), 8, '0',STR_PAD_LEFT)
                             ^^^

With that fix in place everything works fine.

Working link

codaddict
Yes yes yes, thank you so much. I was writing the functions together so fast, I copy+pasted the line 6 times, spreading the problem before I could find it. You saved me sanity. :)
John