Kacy
Kacy

Reputation: 3430

php multiple keys for a single value

Current Design

I'm making a chatting app where any 2 random users can talk.

On the server (in php), I have an array where I store the client pairs, and the key used to access these pairs is one of the client's IDs.

The reason I don't like this is I have to store the client pair in the array twice. I don't know which client is going to disconnect first, so I hash it twice, once for each client id.

In case this isn't clear yet, the process is: client A and B are chatting. Client B disconnects, so I access the pair with key B, figure out the other client's id is A, then unset both elements using keys A and B.

Question

Any better ideas ? It would be nice if 2 keys could be used to access the exact same element in an array, but I don't think that exists.

p.s.

(This client pair object may sound useless based on the description, but it also holds each client's corresponding socket which I can use to send messages to from the server when a disconnection occurs.)

How I'm picturing this with code:

/* The server receives a message from a client with id 1000 that he has left chat */

$client_pairs = array();  //map holding all client pairs currently chatting

connectClients( $client1, $client2 )
{
    $client_pairs[$client1 -> id] = array( $client1, $client2 );
    $client_pairs[$client2 -> id] = array( $client2, $client1 );
}

disconnectClient( $client_id )
{
    $client_pair = $this -> client_pairs[$client_id] 
    $client2 = $client_pair[1];

    unset( client_pairs[$client_id] );
    unset( client_pairs[$client2 -> id] );

    /*
       do stuff with the $client_pair
    */
}

Upvotes: 0

Views: 92

Answers (1)

user488187
user488187

Reputation:

You could have two arrays: $users and $sessions. Let's say, for example, that you, have two users: client_id1 and client_id2. You could then:

$sessions[] = your session information, e.g. sockets, plus both client_ids
end($sessions);
$sessId = key($sessions);
$users[$cliend_id1] = $sessId;
$users[$cliend_id2] = $sessId;

When someone disconnects, use their ID as:

$sess = $sessions[$users[$id]];

$sess then should have everything you need.

Upvotes: 1

Related Questions