0

Can I merge an array, or remove duplicates from an array in PHP >=5.4 using a closure, in the same fashion as it can be done in Objective C using a block, or in C++ using a lambda ?

  • Is it possible to use a predicate/closure/block/lambda as a parameter to such functions.

I.e:

$a = array('blah','bleh');
$b = array('blih, 'bloh');
$arr = array_merge( function() use (&$a,&$b) { return $a == $b ? true : false; } );

(Above example is oversimplified, I want to do this for Objects).

  • Can it be done inline or should I always define the closure as an $var ?
  • Is there a performance gain, or does it run the same ?
11
  • 1
    You'd probably use array_filter with a closure to eliminate duplicates; and yes, it is perfectly possible with an array of objects Commented Mar 28, 2013 at 16:26
  • Thank you @MarkBaker make an answer and you'll get the kudos :) Is that the right syntax btw ? Commented Mar 28, 2013 at 16:27
  • @Alex .. what would be the expected output since you want to merge not filter ... ? Commented Mar 28, 2013 at 16:27
  • @Baba in this case an array of merged arrays of objects without duplicates I would hope. Commented Mar 28, 2013 at 16:29
  • So, array_unique(array_merge())? Commented Mar 28, 2013 at 16:32

1 Answer 1

2

You can probably use array_filter() for this. My guess is that you need to filter 1 array as parameter and add the second array as use(). When the current value is not in the array passed in use(), you can add it. http://php.net/manual/en/function.array-filter.php

This only if you need to check based on a value inside the object ofc as $a == $b can be tricky with objects ;)

Sign up to request clarification or add additional context in comments.

2 Comments

Huh, that is very interesting. Thank you for linking this, I see they already used a function callback, I assume I could just pass a closure to this as well? Kudos for the cleanest solution
Closures and callables are a bit off in PHP. Here's some more information regarding callables. php.net/manual/en/language.types.callable.php As of 5.4 the type Callable has been added and as of 5.3 closures have been added. Before that you had specific functions which allowed a 'function_name' or array($my_obj, 'method_name') to be faked into a 'callable' parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.