0

I am currently working on room assigning, how do I randomize array from only indexes 1 to 3? I have 4 indexes in my array.

$arrayroom = array("1","2","3","4");
$check1 = "SELECT COUNT(*) AS Total FROM grade_7 WHERE Room_Number = '1' ";
    $ch= mysqli_query($conn,$check1);
    $d = mysqli_fetch_assoc($ch);
    if($d['Total'] < 40){
        $room = $arrayroom[0];
     }
     else{
        $room = array_rand($arrayroom);
     }

2 Answers 2

1
  • You can split the array into two parts.
  • Shuffle the first part and keep the second part as is.
  • Merge both parts to get your result.

Snippet:

<?php

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");

$randomize = array_slice($input,0,3);
$keep_safe = array_slice($input,3);
shuffle($randomize);
print_r(array_merge($randomize,$keep_safe));

Demo: https://3v4l.org/HVMc8

Sign up to request clarification or add additional context in comments.

Comments

0

You can use this simple function for retrieving your desired output:

function arrayRangeRand(&$arr, $s, $e){
    $tmp = [];
    for($i=$s;$i<=$e;$i++){
        $tmp[] = $arr[$i];
    }
    shuffle($tmp);
    foreach($tmp as $ind=>$val){
        $arr[$s+$ind] = $val;
    }  
}

 arrayRangeRand($data, $firstInd, $lastInd0);

Demo

Here for loop collects values from-to, then shuffle them, and then replace old values with new ones with referred indexes. & mutates your original data array, so, you don't need to return anything.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.