Reputation: 688
I know this seems like something that should be averted by design, but let's just say it is bitterly needed: Is it possible to reference the key belonging to a value while it is being initialized?
Here is what I imagine it to be (not exactly the case in which I need it, but the key is primitive as well):
$array = array(25 => "My key is " . $this->key);
I need this because the array key is used in each value. Actually the value is another array which has a value in which the first array key is used. Like I said in the comments, I want to keep it DRY. Doing it is no problem, but I want to do it good ;)
Upvotes: 1
Views: 127
Reputation: 10253
If you are writing an array yourself you can just put key value to array value like:
$array = array(25 => "My key is 25");
If you are have an array already you can use a foreach
and add all keys to it's values:
foreach($array as $key => $value) {
$array[$key] = sprintf('%s %s', $value, $key);
}
Or if you just want to have an array of keys of existing array you can use either array_flip if you want to maintain key=>value, but have keys and values flipped. Or you can use array_keys if you want just an array of keys.
To make what you want: initialize an array somewhere and do not add any keys to it's value you can implement ArrayAccess, Countable and have:
public function offsetGet($offset) {
return isset($this->container[$offset])
? $this->container[$offset] . ' ' . $offset
: null;
}
or something like this. But in this case you need to have a variable that contains this array to be an instance of your ArrayAccess
implementation. And depending of usage of this class you probably will need to implement more interfaces.
Upvotes: 1
Reputation: 318478
No, there is no way to reference the key when defining the value. Except maybe writing a preprocessor that embeds it in the string. But that would only work for primitive values.
Upvotes: 0