ady adryan
ady adryan

Reputation: 25

PHP: array_rand arrays

I have this array:

$nonTerminals = array("S","A","B");
$grammar = array(
"$nonTerminals[0]" => "aA",
"$nonTerminals[1]" => array("aA","bB"),
"$nonTerminals[2]" => array("bB","b")
);

and I use this for random values:

$rand_keys = array_rand($grammar, 2);
echo $grammar[$rand_keys[0]] . "\n";

But this is wrong, because it's give me some errors.

Upvotes: 0

Views: 141

Answers (1)

MrSkippy
MrSkippy

Reputation: 348

You can do it like this:

$nonTerminals = array("S","A","B");
$grammar = array(
"$nonTerminals[0]" => "aA",
"$nonTerminals[1]" => array("aA","bB"),
"$nonTerminals[2]" => array("bB","b")
);

$rand_keys = array_rand($grammar, 2);
if (!is_array($grammar[$rand_keys[0]]) {
    //This checks if the value is an array or not.
    echo $grammar[$rand_keys[0]];
}
else {
    //it is an array, so echo a random value from that array;
    echo $grammar[$rand_keys[0]][rand(0, 1)];
}

Upvotes: 1

Related Questions