Skip to content

Conversation

@rundef
Copy link
Contributor

@rundef rundef commented Feb 14, 2016

I needed to count the number of elements in an array ...
I saw that this feature has been talked about in issue #33

I wasn't sure if I should have created a new filter |count for objects only ... Tell me what you think!

public static function length($s)
{
return strlen(utf8_decode($s)); // fastest way
return is_string($s) ?
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

imho it should be something like

public static function length($s)
{
    if (is_array($s)) {
        return count($s);
    } elseif ($s instanceof \Traversable) {
        return iterator_count($s);
    } else {
        return strlen(utf8_decode($s)): // fastest way
    }
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (is_array($val) || $val instanceof \Countable)

@xificurk
Copy link
Contributor

A test would be nice ;-)

@rundef
Copy link
Contributor Author

rundef commented Feb 14, 2016

Thanks for the quick feedback :)

@dg dg closed this in 5d5520a Feb 19, 2016
@dg
Copy link
Member

dg commented Feb 19, 2016

Thanks, merged

if (is_array($s) || $s instanceof \Countable) {
return count($s);
} elseif ($s instanceof \Traversable) {
return iterator_count($s);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this (may) mutate the iterator, imo it's best to let decide the programmer.

iterator_count() is not guaranteed to retain the current position of the iterator.
http://php.net/iterator_count

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants