note 111862 added to function.array-filter

From: Date: Fri, 05 Apr 2013 11:58:54 +0000
Subject: note 111862 added to function.array-filter
Groups: php.notes 
Request: Send a blank email to php-notes+get-194349@lists.php.net to get a copy of this message
breich at reich-consulting dot net made an awesome function, but it has a poor performance, and is bloated. here is a shorter version: <?php function array_remove_keys($array, $keys = array(), $callback=null) { if(empty($array) || (! is_array($array))) { return $array; } if(is_string($keys) && !is_array($keys=explode(',',$keys))) { return $array; } foreach($keys as $key) { $key=trim($key,' '); if(!$callback || !$callback($array[$key],$key)) unset($array[$key]); } return $array; } ?> i decided to let here stay 2 conditions, even though they can be rewritten to 1. unsetting is faster than array_diff_keys. sometimes, people separate strings like 'a, b, c' or 'a , b , c'... i added support for those, since they are essentially the same list. i also added a callback option, which you specify a function and it will give the value and the key to it. p.s.: php uses short-circuit evaluation. example: !$callback || !$callback($array[$key],$key) if $callback is empty, it doesn't try to run $callback(). why? because !$callback || !$callback($array[$key],$key) will be true, no matter the value of !$callback(). so, to save resources and time, php jumps if !$callback is true ---- Server IP: 69.147.83.199 Probable Submitter: 77.54.215.164 ---- Manual Page -- http://php.net/manual/en/function.array-filter.php Edit -- https://master.php.net/note/edit/111862 Del: integrated -- https://master.php.net/note/delete/111862/integrated Del: useless -- https://master.php.net/note/delete/111862/useless Del: bad code -- https://master.php.net/note/delete/111862/bad+code Del: spam -- https://master.php.net/note/delete/111862/spam Del: non-english -- https://master.php.net/note/delete/111862/non-english Del: in docs -- https://master.php.net/note/delete/111862/in+docs Del: other reasons-- https://master.php.net/note/delete/111862 Reject -- https://master.php.net/note/reject/111862 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#194349) next »