23

Is it possible in php to make an array an array key as well?

Example:

array(
   array('sample', 'abc') => 'sample value'
);
11
  • 12
    no, this is not possible. array keys must be integers or strings. this is explained in php.net/manual/en/language.types.array.php Commented Sep 5, 2012 at 14:08
  • You could, theoretically, serialize() the array into a string to use as an array key, but I can't see why your design would require this and I don't actually advocate doing it. It would be fraught with problems, like having to reserialize every time you needed to change it. Commented Sep 5, 2012 at 14:09
  • not only that it is not possible, but I don't even see a practical use for it - indexes and assoc keys in all programming languages (supporting them) to my knowledge are scalar values Commented Sep 5, 2012 at 14:10
  • PHP array keys can be integer and keys only.. Commented Sep 5, 2012 at 14:11
  • @IvanHušnjak compound key hashmaps would be one practical use for it. One can use SplObjectStorage for that though. Commented Sep 5, 2012 at 14:11

4 Answers 4

13

No, if you read the manual

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

And :

The key can either be an integer or a string. The value can be of any type.

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

Comments

13

This is not possible - array keys must be strings or integers.

What you could do is use serialize:

$myArr = array( serialize(array('sample', 'abc')) => 'sample value');

Which will be the same as:

$myArr = array( 'a:2:{i:0;s:6:"sample";i:1;s:3:"abc";}' => 'sample value');

and could be accessed like:

echo $myArr[serialize(array('sample', 'abc'))];

But note that the serialised string which would be the unique identifier for the array item is clearly fairly complicated and almost impossible to type by hand.

3 Comments

This is so scary to look at...
yes.. scary but efficient i think.. thanks..
Not efficient enough to be the accepted answer? ;)
1

PHP arrays can contain integer and string keys while since PHP does not distinguish between indexed and associative arrays. Look for php manual Php Manual

Comments

-3

whats wrong with

array(
    'sample value' => array('sample', 'abc')
);

you could then do

foreach($array as $string => $child){
...
}

and use the $child for whatever purpose

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.