I think we can first talk about clearer code for your use case. You clearly are creating some kind of person, so lets represent that with a person class.
We've got quite a complex creation scenario, we could put it in the constructor, but I think the best thing to do is create a factory class for this.
Given that, we can use tricks like GetRandomElement to ease the syntax. However, I don't think we need to generalise further. I'm not keen on foreach-ing through the properties or anything like that, I think holding the arrays of your possible values distinct is more declarative.
public class Person{
public string Sex { get;set;}
public string Age {get;set;}
public string Beauty { get;set;}
}
public class RandomPersonFactory{
private Random random;
private string[] SexChoices = new[] { "Man", "Woman" };
private string[] AgeChoices = new[] { "Child", "Teen", "Young", "Middle-aged", "Elderly", "Old" };
private string[] BeautyChoices = new[] { "Beautiful", "Pretty", "Normal", "Plain", "Ugly" };
public RandomPersonFactory(Random random){
this.random = random;
}
public Person CreatePerson(){
return new Person {
Sex = GetRandomElement(this.SexChoices),
Age = GetRandomElement(this.AgeChoices),
Beauty = GetRandomElement(this.BeautyChoices)
};
}
private T GetRandomElement<T>(T[] array){
return array[this.random.Next(array.Length)];
}
}
You could organize your code like this; But if you aren't genuinely changing the quantity and type of traits on individual persons at run time it's needless complexity and misdirection. Ask yourself whether you can have a person without a sex trait, or age trait etc. In this case I would write the factory in a similar way, but I would build up an collection of traits one trait at a time in the CreatePerson method and then create the person with that collection.
public class Person2{
public IList<Trait> Traits {get;set;}
}
public class Trait{
public string Name {get;set;}
public string Value {get;set;}
}
mygetrandom(array)anyways, so you'd be saving nothing in lines-of-code terms.$names = array('sex', 'age', 'beauty');, then use variable-variables to access each array in turn:foreach($names as $name) { $str = array_rand($$name); }