A while back, there was a thread discussing adding a specific function
for removing elements from an array by value. Rasmus L. noted that
when the values are unique, they would be better represented as keys:

> The problem is that it is a rather unusual thing to do. I don't mean
> removing an element, that is very common, but you are implying that you
> know you don't have duplicates and you want a fast way to remove an
> element by value in that case. To me that means you built your array
> badly. If the values are unique then they should be the keys, or at
> least a representation of the value should be the key such that you
> don't need to scan the entire hash for the element when you need to
> access it. And removal is just like any other access.

When I come across situations where an array's properties match those
of a set, I create array "sets" by duplicating keys and values:

array("val1" => "val1", "val2" => "val2");

This approach has several benefits:

- Form the union of values using the "+" operator (which forms unions
through use of keys)
- Fast, easy removal of values through unset (e.g., unset($elements["val1"]))
- Standard handling of values in for loops:
for ($elements as $element) {
  echo $element;
}

Writing a userland function to create array sets from
numerically-indexed arrays (avoiding the duplication of typing the key
and value) is indeed trivial:

function create_set($arr) {
  return array_combine($arr, $arr);
}

$set = create_set(array("val1","val2"));

However, I find that the use of array sets is very common and helpful
to me, and I see many situations where a developer would have been
better served by leveraging the key to store the value. I suspect many
PHP users don't understand the nature of PHP arrays. I'm wondering if
adding a function (or language construct) for creating array sets
would prove helpful (just because of the vast amount of code which
could make use of it) and facilitate the education of developers so
they might better leverage the benefits of the underlying hash map
structure when their array is essentially a set and they wish to
perform operations such as removing an item by value.

Adam

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to