Continue not going to loop start
I am having a bit of trouble understanding this bug. Here is the code:
function filter_optionsfordash(array $data,$dash) {
$filtered_options = array();
$len = strlen($dash);
foreach ($data as $k => $value) {
if (substr($k,0,$len) === $dash) {
$option_name = trim(str_replace($dash . '_','',$k));
switch ($option_name) {
case 'displayColumns':
$value = explode(',',$value);
break;
case 'dashletTitle':
$option_name = 'title';
break;
case 'id':
case 'module':
case 'action':
case 'configure':
case 'to_pdf':
continue;
break;
}
$filtered_options[$option_name] = $value;
}
}
return $filtered_options;
}
What I am trying to do here is to filter some values from the give array (in this case it will be the $_POST
) which start with the given name ($dash
), but I want to filter out the ones that are 'id', 'module', 'action', 'configure' or 'to_pdf'.
So what I thought would work is a 'continue'. Since the switch statement isn't a loop, 'continue' should go to the start of the loop (the foreach), but apparently this doesn't happen. I am still getting the key names I don't want in the array.
I have found a solution, by changing the code a bit, but I would reall开发者_如何学Goy like to understand why this doesn't work.
The 'continue' should send me back to the foreach!!
http://docs.php.net/continue says:
continue is used within looping structures to skip the rest of the current loop iteration [...]
Note: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.
You need to use continue 2 instead:
function filter_optionsfordash(array $data,$dash) {
$filtered_options = array();
$len = strlen($dash);
foreach ($data as $k => $value) {
if (substr($k,0,$len) === $dash) {
$option_name = trim(str_replace($dash . '_','',$k));
switch ($option_name) {
case 'displayColumns':
$value = explode(',',$value);
break;
case 'dashletTitle':
$option_name = 'title';
break;
case 'id':
case 'module':
case 'action':
case 'configure':
case 'to_pdf':
continue 2;
break;
}
$filtered_options[$option_name] = $value;
}
}
return $filtered_options;
}
精彩评论