How to retrieve values from two arrays using the same randomly generated index?

Viewed 49

I want to access and display one value from each of the arrays (which have the same index) using a randomly generated index.

My code:

$userRank = array(
    "Nightowl",
    "Demon Hunter",
    "Shadow Walker",
    "Legend"
);

$userLevel = array(
    "Level 5",
    "Level 10",
    "Level 15",
    "Level 20",
);

$deck = array();    
foreach($userRank as $rank){
    foreach($userLevel as $level){
        $deck[] = array("level" => $level, "rank" => $rank);
    }
}

shuffle($deck);
$getVal = array_shift($deck);

echo $getVal['level'] . ' ' . $getVal['rank'];

The end result of this is that the array retrieves random values from the provided arrays.

e.g. Level 10 Nightowl or Level 20 Shadow Walker

edit: i'm already aware if you use multidimensional array you can just assign each to each other but I want to do it with 2 separate arrays.

2 Answers

Are you expecting something like this? Here we are using array_map and returning array of level and rank from the function.

Try this code snippet here

<?php
ini_set('display_errors', 1);
$userRank = array(
    "Nightowl",
    "Demon Hunter",
    "Shadow Walker",
    "Legend"
);

$userLevel = array(
    "Level 5",
    "Level 10",
    "Level 15",
    "Level 20",
);

$deck=array_map(function($uL,$uR){
    return array("level" => $uL, "rank" => $uR);//returning array with level and rank
},$userLevel,$userRank);

shuffle($deck);
$getVal = array_shift($deck);

echo $getVal['level'] . ' ' . $getVal['rank'];

i'm already aware if you use multidimensional array you can just assign each to each other but I want to do it with 2 separate arrays.

It seems to me that the other answer does not satisfy your conditions. This task can be done much more simply in just two lines.

It is only wasteful/indirect programming practices to combine the arrays, shuffle the arrays, then modify the array (cut the first element off), when you just want to access a single element from each array using one random key/index -- this way, you may re-use the original (undamaged) arrays "down-script".

This is the most direct method to use:

Code: (Demo)

$rand_index=rand(0,sizeof($userRank)-1);  // generate a random key/index
echo "{$userLevel[$rand_index]} {$userRank[$rand_index]}";  // display the desired values

Possible Output:

Level 10 Demon Hunter
Related