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:
- It’s not nice to create a list of functions in a global archive "do it all".
- 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.
- 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()
– Pedro Sanção