0

I need to make a key name from a array a reference to a different variable.

Like this:

$keys = array('name' => 'abc');

$arr[&$keys['name']] = array();

But it doesn't work:(

is there any solution?

4
  • 1
    What exactly are you trying to achieve? Commented Mar 13, 2012 at 21:57
  • because the name key may change, and I want the 2nd array to automatically change too Commented Mar 13, 2012 at 21:58
  • Associative indexes cannot be references. You will have to rethink your program design. Consider nesting arrays, like $keys = array('name' => array('abc' => array())); Commented Mar 13, 2012 at 22:01
  • While it won't be a straight-forward solution to your problem, you may consider looking into SplObjectStorage as it may offer some clues. Since objects are implicitly passed around by reference, so it could get you moving in the right direction. Commented Mar 13, 2012 at 22:30

5 Answers 5

4

Associative (or numerical) indexes cannot be references.

Just do:

$arr[$keys['name']] = array();
Sign up to request clarification or add additional context in comments.

Comments

1

Leave the & away and ensure that $arr is set to an array before:

$arr = array();
$arr[$keys['name']] = array();

Comments

1

Take off the reference:

$keys=array("name"=>"abc");

$arr=array();

$arr[$keys["name"]]=array();

var_dump($arr);

The output is:

array(1) {
  ["abc"]=>
  array(0) {
  }
}

2 Comments

but if I change $keys['name']] the key name in $arr wont change.. this is why i wanted it to be a reference in the first place
You aren't changing $keys["name"]. You still have $keys["name"]==="abc";.
1
<?php
$arr = array("foo" => "bar", 12 => true);

echo $arr["foo"]; // bar
echo $arr[12];    // 1
?> 

php.net/array !!! there is a text, befor u ask a question , it says that u shoult REALLY search befor u ask , the first ehtry in google , the first ehtry on php.net <- the very first place to look 4 php cuestions

Comments

1

You can't change the key of an array element using a reference, as you want.

You need to create a new one, and unset the previous:

$key = 'abc';
$array[$key] = 'value';

// to change the key:
$new_key = 'def';
$array[$new_key] = $array[$key];
unset($array[$key]);

You wanted something like the code below, but it does not exist nothing like that in PHP:

$key = 'abc';
$array[&$key] = 'value'; // this is not legal in PHP
$key = 'def'; // (this was supposed to change the key)

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.