<?php $num = 0; $arrmsg1[0] = 0; foreach ($arrmsg as $value) { $arrmsg1[$num] = $value; $num++; if ($num == ($Param['page']-1)*5+4) break; } var_dump ($arrmsg1); ?> 

The var dump shows that there is only one element in the $ arrmsg1 array — 0; How can one either interrupt foreach without losing data on the nth iteration or iterate from the nth element?

Update

There is a list of users with whom there was a correspondence,

 $Param1 = "SELECT `from`, `to` FROM `messages` WHERE `to` = '$_SESSION[USER_LOGIN]' OR `from` = '$_SESSION[USER_LOGIN]'"; $Param2 = '/messages/main/page/'; $Result = mysqli_query($CONNECT, $Param1); $n[0] = 0; while ($Row = mysqli_fetch_assoc($Result)) { If ($Row['from'] == $_SESSION['USER_LOGIN']) $arrmsg[$n] = $Row['to']; else $arrmsg[$n] = $Row['from']; $n[0]++; } $arrmsg = array_unique($arrmsg); 

It is necessary to bring them to 5 per page.

  • What are you trying to do in general? Looks like array_slice - Minor
  • SELECT distinct if (to = '$_SESSION[USER_LOGIN]', from, to) as user FROM messages WHERE to = '$_SESSION[USER_LOGIN]' OR from = '$_SESSION[USER_LOGIN]' limit 5 offset 5 and standard pagination. - Petty
  • This code should be digested, I don’t quite understand it) what it means if (to = '$ _SESSION [USER_LOGIN]', from, to) - Alexander
  • Everything, understood if to = '$ _SESSION [USER_LOGIN]' THEN from else to - Alexander
  • @ Small Please post your comment as a response. - Nicolas Chabanovsky

1 answer 1

It would be more reasonable not to read all the data on the application and aggregate there, but to count the list of interlocutors directly to the DBMS by a request:

 SELECT distinct if (to = :user_login, from, to) as user FROM messages WHERE to = :user_login OR from = :user_login limit 5 offset 5 

And immediately in the request, you can make a pagination.

In the comments did not mention, because it was evident from the use of mysqli_query - the if ( condition, then, else) from the mysql dialect and is not available in all DBMSs. To match standard SQL you can rewrite case

 SELECT distinct case when to = :user_login then from else to end as user FROM messages WHERE to = :user_login OR from = :user_login 

It is still more productive to calculate the DBMS than to read the table in the same volume, transfer and aggregate on the application, but on large volumes of correspondences of a particular user (even if it is being written to only a couple of people, but extremely intensively), it can give problems - performing a distinct over the calculated field the operation is not the cheapest and is not covered by indices. It will be possible to be perverted by different methods, but more often they make a separate aggregated table of dialogs: who spoke to whom, when, a pointer to the last message - this can all be obtained by reading the table of messages, but not always optimally.

  • It worked) so far so let it work, about the second method is not yet clear.) - Alexander