Check whether array is associative in a class

Asked

Viewed 51 times

3

I have a class where I need to do certain checks on an array, such as checking whether it is associative or indexed. I know there is no native function in PHP that does this, so I could use the example below.

function isAssoc($arr)
{
    return array_keys($arr) !== range(0, count($arr) - 1);
}

Example taken from here.

But since I’m working with object orientation and I’d like to do things the right way, I know that:

  1. It’s not nice to create a list of functions in a global archive "do it all".
  2. The class where I am running the check should not know how to do the check, just check, so a clousure wouldn’t be a good idea either.
  3. Since I want my class to be simpler to use I don’t see the point of injecting a dependency into a class that treats arrays in the method signature, I just wanted to check that array, as a native function does.

In short, I wanted to implement something like the code below, but in the right way:

public function __construct($name, $content = null, $attributes= null)  
{
    if(is_assoc($content){
        // 
    }
    else{
       //
    }
}
  • I suggest creating a class helper with static method(s) (s): ArrayHelper::isAssoc()

1 answer

1

I thought here of some ways to solve this problem.

The first is to use a global function. Not everything in your application needs to be object-oriented or there is only one right way to do things. In that case I see no problem that it’s a global function if it really makes sense.

Another way is to create one trait and insert her into your class, something like that:

trait ArrayUtils 
{
    function isAssoc(array $arr)
    {
        return array_keys($arr) !== range(0, count($arr) - 1);
    }
}

class MyClass 
{
    use ArrayUtils;

    public function __construct($name, array $content = [], $attributes= null)  
    {
        if($this->is_assoc($content){

        } else {

        }
    }
}

If possible I find it interesting to ensure that the argument sent is an array employing the hinting type, so it is possible to avoid some extra checks in your methods.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.