0

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.

12
  • 1
    Can you post the errors you get? Because now, from what I see, you are trying to echo an array.. Commented Oct 26, 2015 at 20:33
  • 1
    And those errors are? Commented Oct 26, 2015 at 20:33
  • 3
    If the second or third are chosen you're trying to echo an array, probably Notice: Array to string conversion. Commented Oct 26, 2015 at 20:34
  • Use var_dump instead of echo so you can print the contents of the arrays. Commented Oct 26, 2015 at 20:37
  • prntscr.com/8vnrsx Commented Oct 26, 2015 at 20:37

1 Answer 1

1

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)];
}
1
  • No problem :-) Don't forget to accept the answer ;) Commented Oct 26, 2015 at 20:48

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.