I'm currently going through a PHP tutorial and created a form drop down menu. I'm trying to make my code more efficient by moving some of the blocks of code into functions.
Why does the following code not work when making it a function (example 1) but it does work otherwise (example 2)?
Example 1:
<div id="leftnav">
<div class="search">
<form name="search" method="get" action="search.html" id="search">
<input type="text" value="keywords" name="keyword" class="s0" />
<br />
<select name="title" class="s2">
<?php
productSelection(); // This is the function I am referring to
?>
</select>
<br />
<input type="submit" name="search" value="Search Products" class="button marT5" />
<input type="hidden" name="page" value="search" />
</form>
The function is defined as followed:
productSelection() {
sort($titles, SORT_STRING); // Sort array of products
foreach ($titles as $deserts) {
printf("<option value=\"%s\">%s</option>", $deserts, $deserts);
}
Example 2:
<form name="search" method="get" action="search.html" id="search">
<input type="text" value="keywords" name="keyword" class="s0" />
<br />
<select name="title" class="s2">
<?php
sort($titles, SORT_STRING); // Sort array of products
foreach ($titles as $deserts) {
printf("<option value=\"%s\">%s</option>", $deserts, $deserts);
}
?>
</select>
<br />
<input type="submit" name="search" value="Search Products" class="button marT5" />
<input type="hidden" name="page" value="search" />
</form>
$titles
is not available to your function because it is out of scope. Global variables are not available inside of functions unless you pass them as parameters (preferred) or use the global
keyword (not recommended).
productSelection($titles) {
sort($titles, SORT_STRING); // Sort array of products
foreach ($titles as $deserts) {
printf("<option value=\"%s\">%s</option>", $deserts, $deserts);
}
}
And when invoking it:
<?php
productSelection($titles);
?>