Skip to content

Instantly share code, notes, and snippets.

@zeraphie
Last active February 10, 2017 15:12
Show Gist options
  • Save zeraphie/cd77f0d147f812a692fab3f4ea15cc15 to your computer and use it in GitHub Desktop.
Save zeraphie/cd77f0d147f812a692fab3f4ea15cc15 to your computer and use it in GitHub Desktop.
Extract items from an array (or collection for Laravel) using a callback function for comparison
<?php
if(!function_exists('arrayExtract')){
/**
* Extract items from an array and return them using a callback function to
* compare values
*
* @param array $arr
* @param Callable $callback
* @param bool $preserve
*
* @return array
*/
function arrayExtract(array &$arr, Callable $callback, $preserve = false){
$filtered = array_filter($arr, $callback);
if(count($filtered)){
$arr = array_diff_key($arr, $filtered);
if(!$preserve){
$arr = array_values($arr);
}
}
return $filtered;
}
}
<?php
// Note: This is Laravel collection specific
if(!function_exists('collectionExtract')){
/**
* Extract items from a collection and return them using a callback function to
* compare values
*
* @param \Illuminate\Support\Collection $collection
* @param Callable $callback
* @param bool $preserve
*
* @return \Illuminate\Support\Collection
*/
function collectionExtract(
\Illuminate\Support\Collection &$collection,
Callable $callback,
$preserve = false
){
$filtered = $collection->filter($callback);
if(count($filtered)){
$collection = $collection->diffKeys($filtered);
if(!$preserve){
$collection = $collection->values();
}
}
return $filtered;
}
}
<?php
// Arrays
$arr1 = [0, 1, 2, 3, 4, 5];
$arr2 = arrayExtract($arr1, function($value){
return $value > 2 && $value < 4;
});
/**
* Returns this
* array:5 [
* 0 => 0
* 1 => 1
* 2 => 2
* 3 => 4
* 4 => 5
* ]
* array:1 [
* 3 => 3
* ]
*/
$arr3 = ['first' => 0, 'second' => 1, 'third' => 2, 'fourth' => 3, 'fifth' => 4, 'sixth' => 5];
$arr4 = arrayExtract($arr3, function($value){
return $value > 2 && $value < 4;
}, true);
/**
* Returns this
* array:5 [
* "first" => 0
* "second" => 1
* "third" => 2
* "fifth" => 4
* "sixth" => 5
* ]
* array:1 [
* "fourth" => 3
* ]
*/
// Collections
$collection1 = collect([0, 1, 2, 3, 4, 5]);
$collection2 = collectionExtract($collection1, function($value){
return $value > 2 && $value < 4;
});
/**
* Returns this
* Collection {#476
* #items: array:5 [
* 0 => 0
* 1 => 1
* 2 => 2
* 3 => 4
* 4 => 5
* ]
* }
* Collection {#477
* #items: array:1 [
* 3 => 3
* ]
* }
*/
$collection3 = collect(['first' => 0, 'second' => 1, 'third' => 2, 'fourth' => 3, 'fifth' => 4, 'sixth' => 5]);
$collection4 = collectionExtract($collection3, function($value){
return $value > 2 && $value < 4;
}, true);
/**
* Returns this
* Collection {#476
* #items: array:5 [
* "first" => 0
* "second" => 1
* "third" => 2
* "fifth" => 4
* "sixth" => 5
* ]
* }
* Collection {#477
* #items: array:1 [
* "fourth" => 3
* ]
* }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment