1

I believe we could change the values of an array by reference in a foreach loop like this foreach ($arr as $key => &$value)

I want to modify the keys in my case

$input = array(32 => 2, 99 => 4, 100 => 4);

foreach ($input as &$key => $value)
{
    $key = chr($key);  // I want to change the ascii character to a letter
}

I got an error saying, we cannot pass keys by reference. Any suggestions?

Wild Widow
  • 2,359
  • 3
  • 22
  • 34
  • You want to change the key to string? – aldrin27 Sep 06 '15 at 07:35
  • @aldrin27 yes , that is correct, corresponding string literal of the ascii value – Wild Widow Sep 06 '15 at 07:38
  • 1
    This is not a good idea at all: you are trying to change exactly the keys of the array you are currently iterating on. How do you expect the `foreach` loop to handle your attempt to modify the array structure it is currently working on? – arkascha Sep 06 '15 at 07:42
  • 1
    Somethings just aren't meant to be: http://stackoverflow.com/questions/7616572/alternatives-to-pass-both-key-and-value-by-reference – DirtyBit Sep 06 '15 at 07:44
  • 1
    @HawasKaPujaari thanks for the link , very useful :) – Wild Widow Sep 06 '15 at 07:45

1 Answers1

0

Try this if this works:

 foreach($input as $key => $val)
 {
   $key[] = [(string)$key => $val];
 }
 print_r($key);
aldrin27
  • 3,407
  • 3
  • 29
  • 43