1

My array looks like below on var_dump($user_jason):

'Gustav' => 
    array (size=9)
      'sum' => int 8
      'votes' => string '3' (length=1)
      'links' => null
      'comments' => string '2' (length=1)
      'topnews' => null
      'revisions' => string '3' (length=1)
      'translations' => null
      'skipped' => null
      'firstvotes' => null
  '' => 
    array (size=9)
      'sum' => int 6
      'votes' => null
      'links' => string '3' (length=1)
      'comments' => null
      'topnews' => string '3' (length=1)
      'revisions' => null
      'translations' => null
      'skipped' => null
      'firstvotes' => null
'Dennis' => 

Now where my key is empty I am trying to set that key as "anonymous" but I am not sure how to achieve this. I am trying like below :

foreach ($user_jason as $key => $value) {

      if(empty($key)){
         if(empty($key)){
          unset($user_jason['']);
          $key = "anonouymus";
          $user_jason[$key] = $value;
       }

      }
    }

But its still empty, please suggest how can I do this. Sorry for asking may this be easy but I am trying and not able to achieve this.

Thanks!

3
  • 1
    Empty key is in array but new key is added too. Unseting an element is done with unset function. Commented Dec 13, 2016 at 17:53
  • oh now I can see new key got added as "anonymous" so should i unset the key which is empty !, Thanks! Commented Dec 13, 2016 at 17:54
  • It worked like above now ! Commented Dec 13, 2016 at 17:58

2 Answers 2

2

No need for the loop:

if(isset($user_jason[''])) {
    $user_jason['anonymous'] = $user_jason[''];
}
unset($user_jason['']);
Sign up to request clarification or add additional context in comments.

Comments

2

Code

$user_jason[$key] = $value; 

doesn't mean that your empty key will be replaced with some value.

This code means that to your $user_jason array will be added new key $key and previous key (empty one) will still be in your array. You can unset it with unset:

unset($user_jason['']);

1 Comment

Thanks for explaining !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.