php – Check whether array is associative in a class

Question:

I have a class where I need to do certain checks on an array, like checking if it's associative or indexed. I know there is no built-in PHP function 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 right, I know that:

  1. It's not nice to create a list of functions in a global "does everything" file.
  2. The class I'm running the check on shouldn't know how to check, just check, so a clousure wouldn't be a good idea either.
  3. As I want my class to be simpler to use, I don't see any sense in injecting a dependency for a class that handles 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{
       //
    }
}

Answer:

Here I thought 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's only one right way to do things. For this case I don't see a problem with 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 ensure that the argument sent is an array using type hinting , so you can avoid some extra checks on your methods.

Scroll to Top
AllEscort