This site is for tech Q&A. Please keep your posts focused on the subject at hand.

Ask one question at a time. Don't conflate multiple problems into a single question.

Make sure to include all relevant information in your posts. Try to avoid linking to external sites.

Links to documentation are fine, but in addition you should also quote the relevant parts in your posts.

0 votes

I'm trying to make a random question feature of Question2Answer CMS. I would like to pick a random value from an array, but this value needs to be different from a specified value.

$current = '1138';
$randomarray = array("1", "3", "12", "50", "563", "889" ... "1140", "2700", "5290");

I would to sort out a random value from $randomarray, but there is still a chance that value can be 1138 (or programmatically $current). I want to rule out 1138. The random value must be different from 1138.

So, how can I do that?

in Scripting
edited by
edit history

Please log in or register to answer this question.

1 Answer

0 votes

If you need to preserve the original array you can use the function array_diff() to create a copy with the value of $current removed:

$temparray = array_diff($randomarray, [$current]);

If you don't need to preserve the original array use the function unset() to remove the value of $current:


Note that array_diff() returns the result of the operation as a new array, so you must assign it to a variable, whereas unset() modifies the array in-place.

Either way, you can then pick a random index with the function array_rand() and use that index to get the value:

$i = array_rand($array);
echo $array[$i];

Replace $array with the correct array variable (either $temparray or $randomarray).

by (115)
2 19 33
edit history