0

I'm trying to get a random array for specific key.

this is my code so far,

$convert = array(
    'a' => 'Amusing','Amazing',
    'b' => 'Beyond',
    'c' => 'Clever','Colorful','Calm',
    'd' => 'Dangerous','Donkey',
    'e' => 'Endangered',
    'f' => 'Fancy',
    'g' => 'Great',
    'h' => 'Helpful','Humorous',
    );

$txt="baca";
$txt=strtolower($txt);
$arr=str_split($txt);
foreach ($arr as $alfa) {
    echo $alfa." = ".$convert[$alfa]."\n";
}

the output would be :
b = Beyond
a = Amusing
c = Clever
a = Amusing

but I'm trying to get

b = Beyond
a = Amusing
c = Clever
a = Amazing 

Unique value for specific array ('a') in this case. I tried to use array_rand but failed. I would appreciate any advice given..

1 Answer 1

1

This:

array(
    'a' => 'Amusing','Amazing',
    ...
)

is equivalent to:

array(
    'a' => 'Amusing',
    0   => 'Amazing',
    ...
)

You're not specifying a key for the word "Amazing", so it automatically gets a numeric key. It does not in any way actually belong to the 'a' key, even if you write it on the same line.

What you want is:

array(
    'a' => array('Amusing', 'Amazing'),
    ...
)

And then:

$values = $convert['a'];
echo $values[array_rand($values)];
Sign up to request clarification or add additional context in comments.

Comments

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.