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!

2 Answers 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 ]
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any benefit to not using hexadecimal? Is there any extra processing done? I'm using it because it makes it easier for me. Also I guess the main question wasn't about the hex notation but more the setting some key X, Y and Z as opposed to 0, 1, 2.
There's no "benefit" either way, and there's extremely minimal (if any) extra processing. Don't worry about any additional overhead with this method - Using hex and decimal are two perfectly valid and interchangeable ways to declare keys in an array.
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;
   }
}

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.