2

I have the class "list_member":

class list_member
{
  public $id;
  public $email;
  public $lastchange;
  public $active;
  public $hash;
  public $list_id;

  function __construct($id,$email,$lastchange,$active,$hash,$list_id)
  {
    $this->id = $id;
    $this->email = $email;
    $this->lastchange = $lastchange;
    $this->active = $active;
    $this->hash = $hash;
    $this->list_id = $list_id;
  }
}

And i have an array of list_members. Now i want to get the member with the unique id ($this->id) of e.g. 42.

How is this possible without looping through the whole array and checking every single entry?

Venu Joginpally
  • 103
  • 1
  • 4
n0emis
  • 35
  • 6

1 Answers1

1

One option for searching by a class member without doing an array lookup is to index the lookup property with a hash table. This moves the burden from your processor to your memory.

You can modify your original class by including a static map of id and providing a lookup method. Since id is unique in this case, I've demonstrated a validation check that will stop execution by throwing an exception if you try to instantiate two members with the same value.

class list_member
{
  public $id;
  public $email;
  private static $ids = array();

  function __construct($id,$email)
  {
    $this->id = $id;
    $this->email = $email;

    if ( array_key_exists( $id, self::$ids ) ) {
        throw new Exception('Item with id ' . $id . ' already exists.');
    }
    self::$ids[$id] = &$this;
  }

  public static function lookup_by_id($id) {
    return self::$ids[$id];
  }
}


new list_member(5, 'username1@email.com');
new list_member(15, 'username2@email.com');
new list_member(42, 'username3@email.com');
new list_member(45, 'username4@email.com');

$member = list_member::lookup_by_id(45);
echo $member->email; // username4@email.com
Mike
  • 1,647
  • 15
  • 14
  • Thanks. When i create the array, i just do `$members_list[$id] = new list_member(***);` – n0emis May 27 '18 at 16:36
  • All the Data is store in an SQL-Database, so i dont have to worry about the Ids. – n0emis May 27 '18 at 16:43
  • @HannesKeks are you using PDO to retrieve your result set from the database? Their are alternative ways of populating your class object. e.g. `$pdo->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_GROUP, list_member::class)` which will result in an array of `list_member` objects indexed by the first column of your query. That way you don't need to iterate over the database results to build your objects either. – Will B. May 27 '18 at 17:15