phpnode.jsarraysarray-map

Why the extra implode, array_map, etc functions instead of returning simply a string from the start? Trying to move this PHP to node


    private static function getOrdering($sortingColumn, $sortingDirection)
    {
        if ($sortingColumn === 'reportTime') {
            return implode(', ', array_map(function ($column) use ($sortingDirection) {
                return $column . ' ' . $sortingDirection;
            }, ['report_date', 'report_hour', 'report_minute']));
        }
        return $sortingColumn . ' ' . $sortingDirection;
    }

I'm struggling a bit to understand how the combination of implode and array_map are working. Moreso, what exactly does array_map(function ($column) use ($sortingDirection)... mean? The function ($column) (what does this mean, and where does column come from?) is throwing me off a bit. I'm quite new to PHP, so any basic explanation will likely help.

Edit: Apologies. This is far too broad. Perhaps a more pointed question is: I did try something, but I'm wondering why in the case that the sortingColumn is "reportTime", we don't simply return a concatenation of the "report_date", "report_hour", etc along with the sortingDirection appended to each. Running:

$sortingDirection = 'DESC';

echo(implode(' , ', array_map(function ($column) use ($sortingDirection) { return $column . ' ' . $sortingDirection;}, ['report_date', 'report_hour', 'report_minute'])));

gives me what I'd think: report_date DESC, report_hour DESC, etc. Why go through the extra steps of implode, array_map, etc when I could just return the appropriate string right from the start?


Solution

  • I think the docs for PHP's anonymous functions should help.

    PHP functions have function-scope (not block scope like JavaScript). The use keyword is used to pull in outer scoped variables into the anonymous function.

    array_map() is very similar to Array.prototype.map() in JS. It accepts a callback function to execute for each element in the array ($column in your example).

    The JavaScript equivalent would look something like this...

    const getOrdering = (sortingColumn, sortingDirection) => {
      if (sortingColumn === "reportTime") {
        return ["report_date", "report_hour", "report_minute"]
          .map((column) => `${column} ${sortingDirection}`) // array_map()
          .join(", "); // implode()
      }
      return `${sortingColumn} ${sortingDirection}`;
    };
    

    You could definitely return a string with $sortingDirection interpolated, eg

    return "report_date $sortingDirection, report_hour $sortingDirection, ...";
    

    but the issue then is maintainability. Adding, removing or generally altering the list becomes a chore whereas maintaining an array is much simpler. It could even be stored elsewhere say in a configuration file or database.