Search code examples
phparraysobjecttraversal

PHP - Object or Array for Variable Number of Values per Item?


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!


Solution

  • 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.
        }
    }