Rizki Hadiaturrasyid
Rizki Hadiaturrasyid

Reputation: 156

PHP choosing non zero variable randomly

Say I have 5 variables:

$a=2
$b=0
$c=7
$d=0
$e=3

I want to choose one variable randomly that is not zero, do something with it, then set that chosen variable to zero.

Note that I want to know which variable is chosen, for example if I got 7 I want to also know that it's $c, so that I can change its value after reading it.

What is the simplest way to do that?

I was thinking take all variables then randomize first, then check if it's zero, but it doesn't scale well if I had more variables and more zeroes.

Upvotes: 0

Views: 68

Answers (3)

Sang Anh
Sang Anh

Reputation: 11

apply recursive function

function rand_not_zero($arr) {
    $rand_key = array_rand($arr);
    $result = $arr[$rand_key];
    if (!$result)
        $result = rand_not_zero($arr);

    return $result;
}

$array = array($a, $b, $c, $d, $e);
echo rand_not_zero($array);

Upvotes: 1

Muhammad Usman
Muhammad Usman

Reputation: 10148

$a=2;
$b=0;
$c=7;
$d=0;
$e=3;
 $array = array($a, $b, $c, $d, $e);
 $array = array_filter($array, function($a) { return ($a !== 0); });

 echo $array[array_rand($array)];

Upvotes: 1

Obsidian Age
Obsidian Age

Reputation: 42354

First, I would recommend crafting an array that contains all of the target values. You can then filter the zero values out with array_filter(). Then select a random index from the filtered array with array_rand().

You then have a random non-zero value assigned to $filtered_array[$random_index], which you are free to assign to an independent variable, or echo out to the DOM.

<?php

$a = 2;
$b = 0;
$c = 7;
$d = 0;
$e = 3;

$array = [$a, $b, $c, $d, $e];
$filtered_array = array_filter($array);
$random_index = array_rand($filtered_array);

echo $filtered_array[$random_index]; // 2, 7 or 3

This can be seen working here.

Hope this helps! :)

Upvotes: 1

Related Questions