I got some database data inside an array. Now I want to display 3 elements each page request.
Example:
Data: array(1, 2, 3, 4, 5, 6, 7, 8, 9)
First request: 1, 2, 3
Second request: 4, 5, 6
...
Finally I got a solution and here is my code . Thanks everyone for the help
<?php
session_start();
$array1=array(1,2,3,4,5,6,7,8,9);
$i=0;
if(isset($_SESSION["firstthreeids"])){
$value=$_SESSION["firstthreeids"];
$prevarray=explode(",",$value);
$displayids=array_diff($array1,$prevarray);
}
else{
$displayids=$array1;
}
foreach($displayids as $result){
if($i==3){break;}
$check[]=$result;
$i++;
}
if(count($displayids)==3){
unset($_SESSION['firstthreeids']);
session_destroy();
}
else{
if(isset($_SESSION["firstthreeids"])){
$_SESSION["firstthreeids"]=implode(",",$check).",".$_SESSION["firstthreeids"];
}
else{
$_SESSION["firstthreeids"]=implode(",",$check);
}
}
print_r($displayids);
?>
You can use two php functions array_slice and array_merge.
Step#1 Slice the first three elements of the array.
Step#2 Merge These three elements with the remaining array elements.
<?php
function shuffle(arr){
$first_three = array_slice(arr,0,3);
$remaining_array = array_slice(arr,3);
$new_array = array_merge($remaining_array,$first_three);
return $new_array;
}
$numbers_array = array(1,2,3,4,5,6,7,8,9);
shuffle($numbers_array);
?>