Function not working properly in config or templates

Sometime ago I put together a function, with the help of the forum, that gets the value of a set of fields with a prefix and formats them into a list. This was so I could output the list into Schema data. I am converting my SEO over to the new Meta Tags plugin which now support JSON. Trouble is, If i call the function more then once, it complains that it has already been declared and cant be redeclared??? I thought a function called be used as many times as you like.

The function in the controller (it’s a shared controller) looks like this:

function socialprofiles() {
  $fields = site()->content()->toArray('fields');
  function getSocialFields($value, $key) {
    return strpos($key, 'social') === 0 && substr($key, -6)  !== 'handle' && $value !== '';
  }
  $socialValues = array_filter($fields, 'getSocialFields',ARRAY_FILTER_USE_BOTH);
  $profilelist = implode(',', array_map(function($value) {
    return '"' . $value . '"';
  }, $socialValues));
  return $profilelist;
}

Then I call it in the config with:

'sameAs' => [socialprofiles()],

Is there something wrong with the function or the way im calling it, that means it can only be used once?

You cannot declare a function within a function. You’d have to use an anonymous function.

Ahhh I see… this did it…

function socialprofiles() {
  $fields = site()->content()->toArray('fields');

  $SocialFields = function ($value, $key) {
    return strpos($key, 'social') === 0 && substr($key, -6)  !== 'handle' && $value !== '';
  };

  $socialValues = array_filter($fields, $SocialFields ,ARRAY_FILTER_USE_BOTH);
  $profilelist = implode(',', array_map(function($value) {
    return '"' . $value . '"';
  }, $socialValues));
  return $profilelist;
}