Random inside of Random

Asked

Viewed 61 times

0

<?php
// Define um array com alguns sites:
$site[] = 'site1.com';
$site[] = 'site2.com';
$site[] = 'site3.com';
$site[] = 'site4.com';

// Escolhe um valor aleatório (respeitando o total de sites)
$destino = rand(0, (count($site) - 1));

// Redireciona o usuario:
header("Location: " . $site[$destino]);
?>

Hello, I am using this function so that when the user accesses this php, it is redirected to one of these sites. But I wanted to do a Random inside a Random. For example: In the first option would be site1.com and site2.com. Ai in the second site3.com and site4.com option.

So that if the first option is selected randomly, the site1 or site2 would be opened randomly.

1 answer

1

I’ll explain to you better, first you will create a variable called $group that will be an array within this array you will create two more array each containing 2 sites.

$grupo = [ 
    [ 
        'site1', 
        'site2' 
    ],

    [
        'site3',
        'site4'
    ]
];

Think like this you have group A and this group has two values within it A1 and A2

To print this value

// Aqui estamos acessando o primeiro array e acessando o segundo valor dele 'site2'

echo $grupo[0][1];            


// Aqui estamos acessando o segundo array e acessando o primeiro valor dele 'site3'

echo $grupo[1][0];

As their intention is that they return it randomly just add the Rand() function in place of the array’s key identifier.

echo $grupo[rand(0,1)][rand(0,1)];

Here it will randomly access the array and return one of its values also randomly.

Study multidimensional arrays this will be essential, any doubt comment there anything.

  • Dude, I’m kind of doubtful about the way this code works?

  • I made a more complete explanation, any doubt call blz

  • Would that be correct? http://prntscr.com/my30pt Just so you can understand. I have 5 link1s. 3 are more important and 2 less important. So I want to prioritize the 3 links I left separate and the 2 less important ones in a single space, so the 2 less important links are less likely to be seen. If you could check the code and see if it’s right, I’d really appreciate it, man.

  • In this case you will need to perform a check to see how many items there are within the group before. If it is more than one value you use Rand() and let it decide which value should be returned but if it contains only one value you return it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.