Sunday, 20 November 2016

PHP array delete by value (not key)

Borrowed the logic of underscore.JS _.reject and created two functions (people prefer functions!!)


array_reject_value: This function is simply rejecting the value specified (also works for PHP4,5,7)


function array_reject_value(array &$arrayToFilter, $deleteValue) {
$filteredArray = array();
foreach ($arrayToFilter as $key => $value) {
if ($value !== $deleteValue) {
$filteredArray[] = $value;
}
}
return $filteredArray;
}

array_reject: This function is simply rejecting the callable method (works for PHP >=5.3)


function array_reject(array &$arrayToFilter, callable $rejectCallback) {
$filteredArray = array();
foreach ($arrayToFilter as $key => $value) {
if (!$rejectCallback($value, $key)) {
$filteredArray[] = $value;
}
}
return $filteredArray;
}

So in our current example we can use the above functions as follows:


$messages = [312, 401, 1599, 3, 6];
$messages = array_reject_value($messages, 401);

or even better: (as this give us a better syntax to use like the array_filter one)


$messages = [312, 401, 1599, 3, 6];
$messages = array_reject($messages, function ($value) {
return $value === 401;
});

The above can be used for more complicated stuff like let's say we would like to remove all the values that are greater or equal to 401 we could simply do this:


$messages = [312, 401, 1599, 3, 6];
$greaterOrEqualThan = 401;
$messages = array_reject($messages, function ($value) use $greaterOrEqualThan {
return $value >= $greaterOrEqualThan;
});

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...