user3061527
user3061527

Reputation: 49

How upgrade function from create_function to anonymous function

I need to modify the function so that it doesn't use create_function. I want to use an anonymous feature but I don't know how to use it.

function arrayUniqueMerge()
{
    $variables = '$_' . implode(',$_', array_keys(func_get_args()));
    $func = create_function('$tab', ' list(' . $variables . ') = $tab; return array_unique(array_merge(' . $variables . '));');
    return $func(func_get_args());
}

Upvotes: 1

Views: 103

Answers (2)

Dharman
Dharman

Reputation: 33400

I tried to understand the purpose of your function, but my conclusion was that it is dependant on the PHP version you have build it for.

However, I have come to realize that most likely in PHP 7 your function can be refactored to just the following:

function arrayUniqueMerge2(...$args) {
    return array_unique(array_merge(...$args));
}

Testing it with the sample data:

print_r(arrayUniqueMerge2(['a', 'b'], ['b', 'c'], ['c', 'd']));
//Array ( [0] => a [1] => b [3] => c [5] => d )

Upvotes: 2

Mattia
Mattia

Reputation: 6534

You can created anonymous function as such:

<?php

$myfunc = function ($x) {
  return $x . ' world';
};

echo $myfunc('Hello'); //Echoes "Hello world"

Read more about anonymous functions in the documentation: https://www.php.net/manual/en/functions.anonymous.php

Also create_function was depreaced in PHP 7.2.0

Upvotes: 0

Related Questions