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?

410

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

    <?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 ( [4] => Alex ) 
        Array ( [3] => Blue ) 
        Array ( [4] => Dale ) 
        Array ( [5] => Matt ) 
    ?>
769

Answer

Solution:

Consider the example below :

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

var_dump($array);

We have the output as below without any change :

enter image description here

When you userand(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

More info on var_dump

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

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.