1

I'm a little new to PHP and I'm not sure if this is used or discouraged or whatever. I'm wondering how PHP handles this kind of array and whether or not I should use it.

The array looks something like this.

$arr = [0x00010000 => $valueOne, 0x00020000 => $valueTwo] // and so on

The value variables represent a single number that is somewhere between the surrounding keys. E.g. valueOne ranges from 0x0001000 to 0x0001FFF. The array is expanded using the same pattern as more values are needed.

Thanks!

4

2 回答 2

4

There's nothing wrong with what you're doing, you're just using a numerically indexed array, but instead of using decimal notation to define the keys, you're using hex notation. PHP handles both cases (decimal and hex) in the same way.

The following in decimal is equivalent:

[ 4096 => $valueOne, 8192 => $value ]
于 2012-08-09T16:08:58.013 回答
2

Arrays are always associative in PHP. There's nothing particularly odd about your code, aside from the square bracket initializer (which is PHP 5.4-only syntax so people avoid using it).

One thing to keep in mind is that foreach() will return the items in the order they were put in. If you do $arr[0x00000010] = $valueThree some time later, it will not come before the item with the index 0x00001000. This lack of order is going to make it impossible to determine whether a key falls between two keys. You would need to use ksort() to keep the items in order.

You're probably better off storing the start and end index of the range as value in an object instead. The logic of determining whether a key falls within a particular range becomes far easier:

foreach($ranges as $range) {
   if($value >= $range->start && $value < $range->end) {
      return $range->value;
   }
}
于 2012-08-09T16:46:03.533 回答