5
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

func_get_args() can be replaced with spread syntax

Per this SO answer while it may only eliminate one line, the call to func_get_arg() can be eliminated with PHP 5.6+ by declaring ...$keys as a formal parameter.

Type declarations can be added as of PHP 7.4

Type declarations can be added when the code is running on a version of PHP 7.4 or newer.

public function add() 

can be updated to:

public function add(mixed ...$keys): void

and

public function getData()

can be updated to:

public function getData(): array

Array syntax can be simplified

Since PHP 5.4 arrays can be declared with the short array syntax i.e. []

So the declaration:

private $array = array();

can be simplified to:

private $array = [];
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.