Santosh Mainali
Santosh Mainali

Reputation: 225

PHP Shouldnot Repeat and should be from an array

I'm trying to build a script that does two thing. 1) The Numbers should not repeat. 2) The numbers should be from an array called $id.

<?php
$a = array(); // final array which will have our id's to display
$id = array(1, 3, 5, 7, 9); //final array should contain a number only from this list
$itemstoshow = 3; // how many items to display
for($i = 0; $i < $itemstoshow; $i++) {
    do {
        $a[$i] = assignid(9);
        $chkid = checkeer($a[$i], $i);
        $chkdata = chkdata($a[$i], $i);
    } while($chkdata == "nonexist" or $chkid == "repeatedid");
}

// display numbers in the array
for($i = 0; $i < $itemstoshow; $i++) {
    echo "Item " . $a[$i] . "--------";
}

// check for redundancy function
function checkeer($x, $y)
{  //first parameter is query aray second is counter
    global $a;
    $err = 0;
    // check if repeating number
    for($i = 0; $i <= $y - 1; $i++) {
        if($x == $a[$i]) {
            $err = 1;
        }
    }
    if($err == 1) {
        return "repeatedid";
    }
}

//check if array $a holds value from $id or not
function chkdata($x, $y)
{
    global $a;
    global $id;
    for($i = 0; $i <= $y - 1; $i++) {
        if($x !== $id[$i]) {
            return "nonexist";
        }
    }

}

//assign id function
function assignid($x)
{
    return rand(1, $x);  
}

problem number 1 solved problem number 2 still not solved please help me. the code should show 3 numbers from 1 to 9 which donot repeat and are in the array $id

Upvotes: 0

Views: 50

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89604

You can use array_rand that selects random keys:

$id = array(1,3,5,7,9);
$result = array_intersect_key($id, array_flip(array_rand($id, 3)));

Or you can shuffle the array and take for example the 3 first items:

$id = array(1,3,5,7,9);
$temp = $id;
shuffle($temp);
for ($i = 0; $i < 3; $i++) {
    $result[] = $temp[$i];
}

Upvotes: 1

FirstOne
FirstOne

Reputation: 6215

You could use a combination of array_rand and array_map to get random values from the array that has the values your basing the randomization. Take a look:

$id = array(1,3,5,7,9); //final array should contain a number only from this list
$itemstoshow = 3;
$values = array_map(function($item) use($id){
    return $id[$item];
}, array_rand($id, $itemstoshow));

print_r($values);

Output:

Array
(
    [0] => 1
    [1] => 3
    [2] => 9
)

Running again:

Array
(
    [0] => 3
    [1] => 7
    [2] => 9
)

Upvotes: 1

Related Questions