We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

# random() method in php

on
Medium Priority
404 Views
hello!

i have a function in php that randomly pairs my set of instructors to my set of subjects.the number of subjects is greater than the number of instructors. how can i fairly/evenly assign subjects to instructors such that no instructor gets too many subjects??

can anyone show me a code in php using the random method that solves this problem?

thanks!
Comment
Watch Question

## View Solution Only

CERTIFIED EXPERT
Top Expert 2006
Commented:
You can also just shuffle the students array, and then assign them in a loop to the instrructors:

<?php

\$students = array('a','b','c','d','e','f','g','h','i','j','k');
\$instructors = array('I','II','III','IV','V');

\$assigned = array();

\$cInstructors = count(\$instructors);
\$cStudents    = count(\$students);

shuffle(\$students);

for(\$i = 0; \$i < \$cStudents; \$i++) {
\$cIns = \$i % \$cInstructors;
if(!isset(\$assigned[\$cIns])) \$assigned[\$cIns] = array();
\$assigned[\$cIns][] = \$students[\$i];
}

echo '<pre>';
print_r(\$assigned);
echo '</pre>';

?>

The \$assigned array, will hold \$instructorId => array(\$student, \$student, \$student) key-value pairs.

-r-

Not the solution you were looking for? Getting a personalized solution is easy.

CERTIFIED EXPERT
Top Expert 2006

Commented:
Sorry, the forloop didn't retrieve the actual instructor Id. Use this instead:

<?php

\$students = array('a','b','c','d','e','f','g','h','i','j','k');
\$instructors = array('I','II','III','IV','V');

\$assigned = array();

\$cInstructors = count(\$instructors);
\$cStudents    = count(\$students);

shuffle(\$students);

for(\$i = 0; \$i < \$cStudents; \$i++) {
\$kIns = \$instructors[\$i % \$cInstructors];
if(!isset(\$assigned[\$kIns])) \$assigned[\$kIns] = array();
\$assigned[\$kIns][] = \$students[\$i];
}

echo '<pre>';
print_r(\$assigned);
echo '</pre>';

?>
##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile