note 118132 added to function.array-unique

From: Date: Sun, 11 Oct 2015 22:57:40 +0000
Subject: note 118132 added to function.array-unique
Groups: php.notes 
Request: Send a blank email to php-notes+get-203936@lists.php.net to get a copy of this message
I created a function for doing array_unique with a custom in_array function. So, if elements are considered in the array passed to this function, the array returned won't include elements that are considered equal and only return the values from the first array that are not considered in the array: <?php function uniqueBy(array $array, callable $in_array_func) { $result = array(); foreach ($array as $key => $item) { if (!$in_array_func($item, $result)) { $result[$key] = $item; } } return $result; } ?> Example usage: <?php $in_array_func = function($item, $array) { $fromBower = function($item) { $result = substr($item, strpos($item, 'bower_components')); return $result; }; foreach ($array as $myItem) { if ($fromBower($item) == $fromBower($myItem)) { return true; } } return false; }; // ... $jss = uniqueBy($jss, $in_array_func); ?> ---- Server IP: 72.52.91.14 Probable Submitter: 202.27.242.65 ---- Manual Page -- http://php.net/manual/en/function.array-unique.php Edit -- https://master.php.net/note/edit/118132 Del: integrated -- https://master.php.net/note/delete/118132/integrated Del: useless -- https://master.php.net/note/delete/118132/useless Del: bad code -- https://master.php.net/note/delete/118132/bad+code Del: spam -- https://master.php.net/note/delete/118132/spam Del: non-english -- https://master.php.net/note/delete/118132/non-english Del: in docs -- https://master.php.net/note/delete/118132/in+docs Del: other reasons-- https://master.php.net/note/delete/118132 Reject -- https://master.php.net/note/reject/118132 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#203936) next »