Theodore Steiner Theodore Steiner - 1 month ago 7
PHP Question

Passing Drop Down Menu Value to CSV

I've got a form that has three drop down menus. In the html the options are named 0, 1 and 2 for validation purposes, and the actual inline text are the different options.

When I push the values to .csv, instead of having it just push the number, I wrote a few

if statements
to rename the variable that was saved. I've got it working, but rather than just have a bunch of
if statements
hanging around I thought I would slip them into a function and just call the function. However, when I do that, the value of whatever option the user selected reverts back to being stored as 0, 1 or 2 in the .csv file.

My question is what is my function missing that is causing it to only pick the numbered value?

HTML:

<select id="semesterSelector" name="semesterSelector" onchange="checkPage5()">
<option value="0">Select</option>
<option value="1">Fall</option>
<option value="2">Spring</option>
</select>


PHP:

$semesterSelector = $_POST["semesterSelector"];

function semesterNameChange(){
if($semesterSelector == 1)
{
$semesterSelector = "Fall";
}
elseif($semesterSelector == 2)
{
$semesterSelector = "Spring";
}
}
semesterNameChange();


Pushing the Value to Csv:

$csvData = [...] $semesterSelector [...]

Answer

In PHP, functions have their own scope. This basically means, that if you're trying to access variables from outside the function, you would either need to pass them in (In between the parenthesis), or you would need to use global to allow outside variables to be used within the scope of your function. In this case, you need to simply add global $semesterSelector at the top of your function.

function semesterNameChange(){
    global $semesterSelector;
    if($semesterSelector == 1)
    {
        $semesterSelector = "Fall";
    }
    elseif($semesterSelector == 2)
    {
        $semesterSelector = "Spring";
    }
}
semesterNameChange();

Another way could be to pass the value directly into the function:

function semesterNameChange($selectValue) {
    if( $selectValue == 1 )
    {
        return "Fall";
    }
    elseif ( $selectValue == 2 )
    {
        return "Spring";
    }
}

$semesterSelector = semesterNameChange($_POST["semesterSelector"]);