winadalwinn winadalwinn - 1 year ago 86
PHP Question

Random name without repeating it self

Please tell me, what is my mistake here:

$myarrayofnames = ["Tisha","Vesta","Josphine"];
$randompick = array_rand($myarrayofnames,1);
if($myarrayofnames[$randompick] === "Tisha") {
$myarrayofnames = ["Vesta","Josphine"];
return $myarrayofnames[$randompick];
elseif($myarrayofnames[$randompick] === "Vesta") {
$myarrayofnames = ["Tisha","Josphine"];
return $mymyarrayofnames[$randompick];
elseif($myarrayofnames[$randompick] === "Josphine") {
$myarrayofnames = ["Tisha","Vesta"];
return $mymyarrayofnames[$randompick];

What I'm trying to do is to pick a random name and make sure the next random name won't be the same as it is now.

Answer Source

i asume, you have this code in some function or so. when you get out of the function and call it again for another name, you begin with same array as before, because you did not 'save' the modified array anywhere;

as it been suggested in comments, you could use shuffle and shift:

class gimmeName{

public $array = array('Tisha', 'Vesta', 'Josephine');

public function giveMeUniqueName(){
    return array_shift($this->array);

working demo here: demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download