Check if array is associative in a class

3

I have a class in which 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-oriented and would like to do things the right way, I know that:

  • It's not nice to create a list of functions in a "do everything" global file.
  • The class where I'm running the scan should not know how to do the scan, just check, so a clousure would also not be a good idea.
  • As I want my class to be of simpler use I see no sense injecting a dependency into a class that treats arrays in the method signature, I just wanted to check out such an 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{
           //
        }
    }
    
        
    asked by anonymous 31.10.2015 / 22:50

    1 answer

    1

    I thought of some ways to solve this problem here.

    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. For this case I see no problem of this being a global function if it really makes sense.

    Another way is to create a trait and insert it into your class, something like this:

    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 make sure that the submitted argument is an array using type hinting >, so you can avoid some extra checks on your methods.

        
    01.11.2015 / 00:37