Skip to content
Advertisement

Selection option in php

I am working on a PHP quiz game and at the moment i am struggling a bit mixing php and html together as i have more previous experience in html. I have the following select option for quiz selection:

<select style="width: 300px" name="quizes" size="10">
  <option onClick="window.location = 'quiz1.php'" >Quiz 1</option>
  <option>Quiz 2</option>
  <option>Quiz 3</option>
  <option>Quiz 4</option>
  <option>Quiz 5</option>
</select>

I was told that this can be made with php code so that the new quizes are added onto it when created. Can somebody help me out with this, i dont quite understand how this would work.

I am not using database for my quizes, each quiz is/will be on one page, with the questions stored in array and the processing of the questions is on the same page.

Advertisement

Answer

Try this. It presumes that the page where the selection is made, is in the same directory as your quiz php pages.

<?php
$dir    = getcwd();
$files = scandir($dir);

foreach($files as $file)
{
    if (strpos($file,'quiz') !== false)
    {
        $fileName = ucfirst(str_replace('.php', '', $file));
        $quizPages[] = array('name'=>$fileName,'file'=>$file);
    } 
}
?>

<select style="width: 300px" name="quizes" size="10">
<?php
foreach($quizPages as $quiz)
{
    echo '<option name="' . $quiz["name"] . '" onClick="window.location = '' . $quiz["file"] . ''" >' . $quiz["name"] . '</option>';
}
?>
</select>

Update for comment.

This is likely due to the fact you have a file called Quizes in that directory also, which having the word quiz in its being caught in the foreach loop. What I would suggest is to change this line

if (strpos($file,'quiz') !== false)

To this

if (strpos($file,'quiz') !== false && strpos($file,'quizes') === false)

Further update. If you want to have a custom name for the quiz I would suggest you use the following naming convention quiz_desired_name.php. So for example If I have a quiz called what animal are you. Then the filename should be quiz_what_animal_are_you.php therefore separating words with underscores.

Then just replace this line

$fileName = ucfirst(str_replace('.php', '', $file));

with this

$fileName = ucfirst(str_replace(array('.php','quiz_','_'), array('','',' '), $file));
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement