3

I want to convert PHP list (array), i.e.

array("start", "end", "coords")

into associative array with truthy values (just to be able to test the presence/absence of key quickly), i.e. to something like this:

array(
    "start" => 1,
    "end" => 1,
    "coords" => 1
)

Is there any more elegant way to do it than this?

array_fill_keys($ar, 1)
9
  • 10
    What can possibly be more elegant than one call to a built-in function? Commented Mar 14, 2012 at 11:01
  • @Felix I know it sounds weird, but I find this way of doing it rather clumsy... Commented Mar 14, 2012 at 11:04
  • You can iterate over the array if it makes you feel better ;) PHP does not have sets so this is really the best you can do. You can create your own function of course: function setify($array) { return array_fill_keys($ar, true);} or something like that. Or what would you expect? Commented Mar 14, 2012 at 11:05
  • is there any function like array_fill_keys? Commented Mar 14, 2012 at 11:05
  • @sandeep: php.net/manual/en/function.array-fill-keys.php Commented Mar 14, 2012 at 11:07

2 Answers 2

5

There is probably no more elegant solution than array_fill_keys($ar, 1).

Sign up to request clarification or add additional context in comments.

Comments

1

There is a function called array_flip that does this.

http://php.net/array_flip

Doing array_flip on an array and then using isset turned out to be much faster than doing in_array for me.

But note that this is only useful when you're going to be searching the array multiple times.

4 Comments

in_array is slow anyways (compared to isset), as it has to do a linear search. array_flip is a possibility but note that the first entry will have a value of 0 and therefore does not evaluate to true (e.g. if($arr[firstEntry])). Of course one should use isset anyways, so the actual values don't really matter (as long as they are not null).
@Tomas: How else are you testing the presence of an element? Just doing if($arr[value]) will give you a Notice: if the key is not in the array.
yes, in_array is slow. But if I am using this method to check if a value exists in an array, it has to process each item in the array anyways. And I'm sure the time to hash a string and make it an array key is longer than the time taken whether it's equal to the $needle. Also, this method takes up more memory - but it's great if you are checking if lots of strings.
@Thomas, then just say $result[$originalArray[0]] = 1 and now you can be assured that every key points to a value that evaluates to true.

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.