lilHar
lilHar

Reputation: 1866

Convert a string with hex values to an array array of boolean values in php

I found a clever bit of code in the site I'm working on that uses hex values to store an array of toggleable variables.

(For example, D in hex being 1101 in binary, means the first toggle is one, the second is off, and the third and fourth are on).

I looked at unpack, but either I didn't understand it or it's not the right function for me. I also considered splitting the whole thing character by character and then sending each character through a switch that then drops values into an array, but that seems way too cumbersome and inelegant.

So, how do I turn a string of hex-based characters into an ordered array of Boolean values?

Upvotes: 2

Views: 251

Answers (1)

lafor
lafor

Reputation: 12776

How about:

function hex_to_bool_array($hex_string, $pad_length = 0) {
   return array_map(
      function($v) { return (bool) $v; },
      str_split(str_pad(base_convert($hex_string, 16, 2), $pad_length, '0', STR_PAD_LEFT))
   );
}

var_dump(hex_to_bool_array('D'));

// array (size=4)
//   0 => boolean true
//   1 => boolean true
//   2 => boolean false
//   3 => boolean true;

var_dump(hex_to_bool_array('7', 8));

// array (size=8)
// 0 => boolean false
// 1 => boolean false
// 2 => boolean false
// 3 => boolean false
// 4 => boolean false
// 5 => boolean true
// 6 => boolean true
// 7 => boolean true

Upvotes: 2

Related Questions