Search code examples
phparraysarray-key

How to replace value of array key?


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!


Solution

  • No need for the loop:

    if(isset($user_jason[''])) {
        $user_jason['anonymous'] = $user_jason[''];
    }
    unset($user_jason['']);