Reputation: 97
Please I need some help. I have the array given below and I want to return random elements from it.
$data = array('Computer', 'Laptop', 'Mouse', 'Keyboard');
$rand = rand(0,count($data)-1);
echo $data[$rand];
The code above works as expected. However, I wan't to be able to exclude specific elements from the returned list as given below:
$exclude = "Mouse";
$data = array('Computer', 'Laptop', 'Mouse', 'Keyboard');
$rand = rand(0,count($data)-1);
echo $data[$rand];
The expected result is that the element specified in $exclude "Mouse"
in this case will not be returned as one of the random elements.
Maybe the mouse element will first be removed from the array as seen below then a random element will be returned:
$data = array('Computer', 'Laptop', 'Keyboard');
Upvotes: 2
Views: 1949
Reputation: 11808
You can prepare a new array and store the strings without excluded string as:
$exclude = "Mouse";
$data = array('Computer', 'Laptop', 'Mouse', 'Keyboard');
$exclude_arr=array();
foreach ($data as $single)
{
if($single !== $exclude)
$exclude_arr[]=$single;
}
//Here you have the array exclude_arr without the exclude string
$rand = rand(0,count($exclude_arr)-1);
echo $exclude_arr[$rand];
execute rand() function as usual and echo it
Upvotes: 0
Reputation: 2788
I think you are right and the best solution for such scales is array filtering. Say,
$exclude = "Mouse";
function noexc($var) {
global $exclude;
return ($exclude != $var);
}
$data = array('Computer', 'Laptop', 'Mouse', 'Keyboard');
$fdata = array_filter($data, "noexc");
$rand = rand(0,count($fdata)-1);
echo $fdata[$rand];
Upvotes: 0
Reputation: 31749
A recursive function may help -
function select_rand($exclude, $array) {
$rand = rand(0,count($array)-1);
if($array[$rand] == $exclude) {
select_rand($exclude, $array);
}
else
{
echo $array[$rand] ;
}
}
$exclude = "Mouse";
$data = array('Computer', 'Laptop', 'Mouse', 'Keyboard');
select_rand($exclude, $data);
Or
$exclude = "Mouse";
$data = array('Computer', 'Laptop', 'Mouse', 'Keyboard');
$temp = array_diff($data, array($exclude));
echo $temp[rand(0, sizeOf($temp))];
Upvotes: 0
Reputation: 5484
You could use array_diff to remove values in $exclude
from $data
.
$exclude = array('Mouse');
$data = array('Computer', 'Laptop', 'Mouse', 'Keyboard');
$excluded_data = array_values(array_diff($data, $exclude));
$rand = rand(0,count($excluded_data)-1);
echo $excluded_data[$rand];
This code removes Mouse
from $data
and then gets random value from new array. Array for random data will be like you described:
$data = array('Computer', 'Laptop', 'Keyboard');
Upvotes: 3
Reputation: 1604
Try this
$exclude = "Mouse";
$data = array('Computer', 'Laptop', 'Mouse', 'Keyboard');
$dummy_data=$data ;
$key=(array_keys($dummy_data,$exclude));
$key=$key[0];
unset($dummy_data[$key]);
$rand = rand(0,count($dummy_data)-1);
//print_r($dummy_data);
if(isset($dummy_data[$rand]))
echo $dummy_data[$rand];
else
echo"Record Missing";
Upvotes: -1