Reputation: 25
function Sign1(){
$check = array(
'23-03-2014' => 'saturday 22 may',
'17-05-2014' => 'friday 16 may'
);
Dateoption();
}
function Sign2(){
$check = array(
'10-02-2014' => 'monday 10 feb',
'15-02-2014' => 'friday 15 feb',
'14-03-2014' => 'friday 14 march'
);
Dateoption();
}
function Dateoption(){
$now = time();
$result = array();
foreach($check as $date => $text) {
if($now <= strtotime($date)) {
$result[] = $text;
}
}
$html = '';
foreach($result as $v) {
$html .= '<option>'.$v.'</option>';
}
return $html;
}
$Content= '
<div class="content">
I am signing up for the following date:<br />
<select name="date[0]">
'. Sign1() .'
</select>
<select>
'. Sign2() .'
</select>
</div>
';
echo $Content;
Why is this not working? It is going wrong @ foreach($check as $date => $text) { but what do i have to change to let this work. I'm doing this So i only have to type the function once instead of copy pasting it everywhere.
Upvotes: 0
Views: 34
Reputation: 1826
This is to do with variable scope. Dateoption cannot see the $check variable. The php documentation describes this as: However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.
You need to pass $check as a parameter to the Dateoption method.
function Sign1(){
$check = array(
'23-03-2014' => 'saturday 22 may',
'17-05-2014' => 'friday 16 may'
);
return Dateoption($check);
}
function Sign2(){
$check = array(
'10-02-2014' => 'monday 10 feb',
'15-02-2014' => 'friday 15 feb',
'14-03-2014' => 'friday 14 march'
);
return Dateoption($check);
}
function Dateoption($check){
$now = time();
$result = array();
foreach($check as $date => $text) {
if($now <= strtotime($date)) {
$result[] = $text;
}
}
$html = '';
foreach($result as $v) {
$html .= '<option>'.$v.'</option>';
}
return $html;
}
$Content= '
<div class="content">
I am signing up for the following date:<br />
<select name="date[0]">
'. Sign1() .'
</select>
<select>
'. Sign2() .'
</select>
</div>
';
echo $Content;
Upvotes: 1