Re: Proposal for a new array function

From: Date: Mon, 08 Feb 2016 17:43:53 +0000
Subject: Re: Proposal for a new array function
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-91126@lists.php.net to get a copy of this message
Hi,
I want to propose a new PHP array method, called has_numeric_keys (or something similar/better), that would have the following method signature: bool has_numeric_keys(array $array) The reason for it is to check if the array passed to it only had numeric keys. Why this method, when you could do it in userland PHP? Answer? Convenience. I found, recently, that I had to perform this kind of check, when patching Zend\Db\Sql\Insert.php. The approach I took was this: return array_keys($arr) !== range(0, count($arr) - 1); Not sure of my approach, I took to Twitter and received the following suggestions, amongst others: function isArrNum($arr) { foreach($arr as $i =>$v){
     if (!is_int($i)) {
       return false;
     }
} return true; } count(array_filter(array_keys($array), 'is_string')) > 0 array_filter([...], 'is_int', ARRAY_FILTER_USE_KEY) This convinced me that it wasn't just me seeing a valid use case for it, and that others have implemented differing solutions when presented with the same situation. Given that, I believe a simple, utility, function such as this would be of help. As for who would implement it, that would be me. I like it. Would like to see it be a bit more generic though, something like (ignore the name, I can't name functions):
array_validate_keys($array, is_int); I say this because it allows for more potential uses (that and I've done exactly the same to check all keys are strings before). - Matt.

« previous php.internals (#91126) next »