What steps can be taken to ensure that disconnected clients are properly removed from the array in a PHP Socket Server?

When a client disconnects from a PHP Socket Server, it is important to remove them from the array of connected clients to prevent errors or issues with handling future connections. To ensure disconnected clients are properly removed, you can implement a mechanism to detect when a client disconnects and remove their socket from the array.

// Check for disconnected clients and remove them from the array
foreach ($clients as $key => $client) {
    $socket = $client['socket'];
    $data = @socket_read($socket, 1024, PHP_NORMAL_READ);
    
    if ($data === false) {
        // Client disconnected, remove from array
        socket_getpeername($socket, $ip);
        socket_close($socket);
        unset($clients[$key]);
        echo "Client $ip has disconnected.\n";
    }
}