0

I need to track a fixed number of items with a variable number of value pairs for each in PHP (7.x or 8.x). Meaning item 1 may have 1 value pair (e.g. "red",32) whereas another item may have 3 value pairs associated with it (e.g. ("blue",99), ("white",45), ("orange", 67).

I need to be able to list all value pairs for each item. Is an array better suited for this task or is using an object easier/faster/more sensible?

Thank you!

1 Answer 1

1

The most sensible option would be to create a KeyValue class and a KeyValueContainer. This would give you type hinting too.

class KeyValue
{
    private function __construct(private string $key, private string $value)
    {
    }

    public function getKey(): string
    {
        return $this->key;
    }

    public function getValue(): string
    {
        return $this->value;
    }
}

class KeyValueContainer implements \Iterator
{
    public function __construct(private array $keyValues = [])
    {
    }
    
    public function current(): KeyValue
    {
        // TODO: Implement current() method.
    }

    public function next(): void
    {
        // TODO: Implement next() method.
    }

    public function key(): int
    {
        // TODO: Implement key() method.
    }

    public function valid(): bool
    {
        // TODO: Implement valid() method.
    }

    public function rewind(): void
    {
        // TODO: Implement rewind() method.
    }
}

Sign up to request clarification or add additional context in comments.

2 Comments

Would you have an example of what you are talking about?
I've added an example in my original post.

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.