Create unique id using recursion

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Create unique id using recursion

Post by papa »

Hi,

I'm stuck on a function I've been trying to do a neat solution for but haven't got the skills apparently.

Looping through an array and see if matches my rand(id). If match, use the same function again and if running out of question or find unique question, end it.

Code: Select all

<?php
 
function randQuestion($questions, $answeredQ) {
    reset($answeredQ);
    $limit = count($questions);
    $q = rand(0, $limit);
        foreach($answeredQ as $answered) {
            if($q == $answered) {
                $question .= "$q vs $answered - match<br />";
                randQuestion($questions, $answeredQ);
            } else $question .= "$q vs $answered<br />";
        }
        return $question;
}
 
echo randQuestion(array("q1", "q2", "q3", "q4", "q5"), array(0, 1, 2, 3));
 
?>
The $question var is just for error coding.
Thanks.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Create unique id using recursion

Post by onion2k »

What are you trying to achieve? I can't see the point of your function.
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: Create unique id using recursion

Post by papa »

Pick a random question out of the question array, and if that question is already in answeredQ array. Pick another random question.

Might have overdone the whole thing.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Create unique id using recursion

Post by VladSun »

Order the questions by random() and then use successive incrementing index to pick up another question ;)
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: Create unique id using recursion

Post by papa »

Hah, thanks man!
Post Reply