Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have the following class:

class MultiArray
{
    private $array = array();

    public function add() 
    {
        $keys = func_get_args();
        $value = array_pop($keys);

        $array =& $this->array;
        foreach ($keys as $key) {
            if (!isset($array[$key])) {
                $array[$key] = array();
            }
            $array =& $array[$key];
        }
        if (!in_array($value, $array)) {
            $array[] = $value;
        }
    }

    public function getData()
    {
        return $this->array;
    }
}

Here's an example on how to use it:

$words = new MultiArray();
$words->add('A');
$words->add('A', 'airplane');
$words->add('C', 'car', 'Nissan');
$words->add('R', 'road', '16th avenue', 'Richmond');

print_r($words);

This will output:

Array
(
    [0] => A
    [A] => Array
        (
            [0] => airplane
        )

[C] => Array
    (
        [car] => Array
            (
                [0] => Nissan
            )
    )
[R] => Array
    (
        [road] => Array
            (
                [16th avenue] => Array
                    (
                        [0] => Richmond
                    )
            )
    )
)

It does the job but I feel like this is bad code. Is there a way to improve this code?

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.