在PHP中有没有办法在同一个switch语句中的另一个case块中访问我在一个case语句块中分配给变量的值?例如,我想在下面的“保存更改”案例块的“修改任务”案例块中访问我分配给$ task_to_modify的值。这是我的代码。任何建议都会有所帮助,因为我是PHP的新手。感谢。
$task_to_modify
switch( $_POST['action'] ) {
case 'Add Task':
$new_task = $_POST['newtask'];
if (empty($new_task)) {
$errors[] = 'The new task cannot be empty.';
} else {
//$task_list[] = $new_task; //original code
array_push($task_list, $new_task);
}
break;
case 'Delete Task':
$task_index = $_POST['taskid'];
unset($task_list[$task_index]);
$task_list = array_values($task_list);
break;
case 'Modify Task':
global $key;
$key = $_POST['taskid']; //taskid is index of selected task from tasks selection list
global $task_to_modify;
$task_to_modify = $task_list[$key];
set_task_to_modify($task_to_modify);
echo "modify task case reached. task_to_modify is " . $task_to_modify;
break;
case 'Save Changes':
global $task_to_modify;
if(in_array($new_task, $task_list)) { //if old value is in the list
$index = array_search($new_task, $task_list); //return index # of old value
$task_list[$index] = $task_to_modify; //replaces old value with newly entered value
unset($task_to_modify); //deletes var so original form will show
}
break;
case 'Cancel Changes': //works correctly
echo 'no changes saved';
unset($task_to_modify);
break;
}