Re: Proposal for a new array function
| From: | Cesar Rodas | Date: | Mon, 08 Feb 2016 17:06:14 +0000 |
| Subject: | Re: Proposal for a new array function | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-91124@lists.php.net to get a copy of this message | ||
On 2/8/16 2:04 PM, Eugene wrote:
> On Mon, Feb 8, 2016 at 3:32 PM, Matthew Setter <matthew@maltblue.com> wrote:
>
>> 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.
array_keys($array) === range(0, count($array)-1)
This is how I check, and it seems a bit faster.
>>
>> As for who would implement it, that would be me.
>>
>> --
>> Kind regards,
>>
>>
>> *Matthew Setter*
>> *Freelance Software Developer & Technical Writer *
>> *Host of Free the Geek <http://freethegeek.fm> |
>> Author of Zend Framework
>> 2
>> Foundations
>> <https://leanpub.com/zendframework2-for-beginners>*
>>
>> w: http://www.matthewsetter.com
>> t: *@settermjd <https://www.twitter.com/settermjd>*
>> g+: *+MatthewSetterFreelanceWriterDeveloper
>>
>> <https://plus.google.com/u/0/+MatthewSetterFreelanceWriterDeveloper/posts
>>> *
>> li: *in/matthewsetter
>> <https://www.linkedin.com/in/matthewsetter>*
>>
>
>
> Usually, checking only numeric keys is not enough. You may also need to
> check if those numeric keys are a sequence starting from 0.
> At least, that was my case when I was implementing MessagePack protocol.
> And I ended up just doing this trivial check: array_values($array) ===
> $array.
>
--
César D. Rodas
Open Source developer
+595-983-161124
PGP: F9ED A265 A3AB C8A1 D145 7368 158A 0336 C707 0AA6