# php - How randomized array keys with rand() works?

324

I'm a bit confused about how this works (the title)? For example, i'm setting an array like this

``````\$array[rand(0, 5)] = 'Alex';
\$array[rand(0, 5)] = 'Blue';
\$array[rand(0, 5)] = 'Dale';
\$array[rand(0, 5)] = 'Matt';
``````

An example of a possible result after a`var_dump(\$array);` of the array :

``````Array
(
 => Blue
 => Dale
 => Matt
)
``````

What happens technically?

410

#### Solution:

your constructing array with random key for each value .rand(0,5) means it take any one number between 0-5 but may be key overwriting issue is here . its the best example . run this one more than one time and know the each output .you can see the key repeating

``````    <?php

\$array1[rand(0, 5)] = 'Alex';
\$array2[rand(0, 5)] = 'Blue';
\$array3[rand(0, 5)] = 'Dale';
\$array4[rand(0, 5)] = 'Matt';

print_r(\$array1);
print_r(\$array2);
print_r(\$array3);
print_r(\$array4);

output:

out put differ each time .here you can see the key repetation .

Array (  => Alex )
Array (  => Blue )
Array (  => Dale )
Array (  => Matt )
?>
``````
769

#### Solution:

Consider the example below :

``````\$array = 'Alex';  //replaced  rand(0, 5) with 0
\$array = 'Blue';  //replaced  rand(0, 5) with 3
\$array = 'Dale';  //replaced  rand(0, 5) with 2
\$array = 'Matt';  //replaced  rand(0, 5) with 4

var_dump(\$array);
``````

We have the output as below without any change : When you use`rand(0, 5)` it takes random value given , hence it keeps changing each time you run and you have different outputs.

`var_dump` — Dumps information about a variable

People are also looking for solutions to the problem: How can I send a followup mail 2 days after user signup in PHP WordPress?

Source