0

I will explain:
I have a socket socket.php file that will add a connection for each user so the user has multiple connections from different devices.

$clients[] = $socketChange; // array_push($clients,$socketChange); // 505
$end = key (array_slice ($clients, -1, 1, TRUE)); // extract 505
$userConexion [$userId] [] = $end; // add to clientID socket 505

what you do is add each connection to the client array and then the last added socket assign it to the corresponding user. so the user can have multiple sessions of different devices and in all will receive the information in real time.

Now what is my question is ...

how can I control of positions, that is, if they connect and disconnect 1k from users for the user number 1001 $ clients he will show me$ clients [1001]how he could restart the counter without removing the users already connected.

i delete clients socket close with unset() array_shift() reorder bad $clients sockets.

example:

$clients[0] = resource 0;
$clients[1,433]  = empty;
$clients[434]  = resource 434;
$clients[435]  = resource 435;
$clients[436,450]  = empty;
$clients[451]  = resource 435;
$clients[452,999]  = empty;
$clients[1000] = resource 1000;

new connexion 1001 add to empty positions.

example:

<?php 

$a1 = array();
$a2 = array();

for ($i=1; $i < 4 ; $i++) { 
    $a1[] = array("hello{$i}" => "hello{$i}");
    $a2[] = array("hello{$i}" => "hello{$i}");
}

echo "<pre>";
unset($a1[1]);
unset($a2[1]);

$a1[] = array("hello11" => "hello11");
array_push($a2, array("hello11" => "hello11"));

print_r($a1); // 0,2,3
print_r($a2); // 0,2,3

// need insert in position empty in this example `1`.
Bryro
  • 222
  • 1
  • 14
  • You want to find the last key? There is a new way to do this in php (and that would make this a duplicate question). Maybe I misunderstand your requirement. – mickmackusa Apr 19 '19 at 22:22
  • @mickmackusa if you can help me find a better way to allocate the sockets per user. I would greatly appreciate it! – Bryro Apr 19 '19 at 22:26
  • I am trying to find a reason not to close with https://stackoverflow.com/a/52098132/2943403 I think I don't follow your question. I suppose I find your question Unclear. Your terminology is confusing to me. "Limit of positions". – mickmackusa Apr 19 '19 at 22:28
  • So you wish to find the lowest available integer key? https://stackoverflow.com/q/22076141/2943403 and https://stackoverflow.com/q/48066561/2943403 – mickmackusa Apr 20 '19 at 00:02

1 Answers1

2

I'm not sure to understand your question, but if you want to add the new connection's data in the first unoccupied index of your array, here is something you can do :

for($i=0; $i<count($clients)+1; $i++) {
  if(!isset($clients[$i]) {
    $clients[$i] = resource 1001;
    break;
  }
}

Use empty($clients[$i]) instead of !isset($clients[$i]) if the index still exist in the array and simply do not have a value anymore.

Charles.C
  • 345
  • 1
  • 3
  • 12