Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose "length" filter, make it work with Countable objects #103

Closed
wants to merge 4 commits into from

Conversation

@rundef
Copy link
Contributor

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!

@@ -366,7 +366,9 @@ public static function capitalize($s)
*/
public static function length($s)
{
return strlen(utf8_decode($s)); // fastest way
return is_string($s) ?

This comment has been minimized.

Copy link
@fprochazka

fprochazka Feb 14, 2016

Contributor

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
    }
}

This comment has been minimized.

Copy link
@dg

dg Feb 14, 2016

Member

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

@xificurk

This comment has been minimized.

Copy link
Contributor

xificurk commented Feb 14, 2016

A test would be nice ;-)

rundef added 2 commits Feb 14, 2016
@rundef

This comment has been minimized.

Copy link
Contributor Author

rundef commented Feb 14, 2016

Thanks for the quick feedback :)

@dg dg closed this in 5d5520a Feb 19, 2016
@dg

This comment has been minimized.

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);

This comment has been minimized.

Copy link
@hrach

hrach Feb 20, 2016

Contributor

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
Projects
None yet
5 participants
You can’t perform that action at this time.