Вопрос

Just wondering how I can easily have two array keys with the same associative value. My current code is:

$arraytest = array(
        'test1', 'test2' => 1,
        'test3', 'test4' => 2,
)

I want the array to work so the following code returns:

$arraytest['test1'] returns 1
$arraytest['test2'] returns 1

etc

thanks for your help, m

Это было полезно?

Решение

you can associate the reference of one variable to two array keys to simulate this situation :

e.g.

$a = 2;

$arraytest = array (
  'test1' => &$a,
  'test2' => &$a
);

This way, as 'test1' and 'test2' point to $a in memory you will always have the value of the "real" $a using 'test1' and 'test2' of the array. However keep in mind using references in arrays should be avoided since this can lead to unexpected program behaviors:

from php.net documentation

"Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value."

More details here => What References Do (php.net)

Другие советы

    $a =array_merge(
      array_fill_keys( array('test','test2'), '1'),
      array_fill_keys( array('test3','test4'), '2') 
    );

    print_r($a);
/*
    Array
    (
        [test] => 1
        [test2] => 1
        [test3] => 2
        [test4] => 2
    )
*/
$arr = asign(array('test','test1'),'2');

//print_r($arr);
/*
Array
(
    [test] => 2
    [test1] => 2
)
*/
$arr = asign(array('test2','test3'),'3',$arr);

print_r($arr);
/*
Array
(
    [test] => 2
    [test1] => 2
    [test2] => 3
    [test3] => 3
)
*/


function asign($key,$val,$arr=array()){

foreach($key AS $v){

$arr[$v]=$val;
}

return $arr;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top