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 avar_dump($array);
of the array :
Array
(
[0] => Blue
[1] => Dale
[2] => Matt
)
What happens technically?
Answer
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
Answer
Solution:
Consider the example below :
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 variableMore info on var_dump