resakse
resakse

Reputation: 83

randomize value in array for specific key

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..

Upvotes: 0

Views: 39

Answers (1)

deceze
deceze

Reputation: 521995

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)];

Upvotes: 1

Related Questions