Returning the success or failure of processing an array using foreach
I have开发者_如何转开发 a PHP function that has an array as a parameter, and I am using foreach
to process the array. My question is, how can i return a true
or false
by using the condition that the function has done the process of the foreach
thoroughly without finding any failure on one of the steps of the process inside the foreach
?
Something like:
function do_process($array_vars){
foreach($array_vars as $array_var) {
//do the process
}
return (foreach process success) ? true : false;
}
That depends on what you mean by "thoroughly".
You can abort as soon as something goes wrong:
function foo($array) {
foreach ($array as $foo) {
if (/* something or other */) {
return false;
}
...
}
return true;
}
Or you can continue through the rest of the array but remember that something went wrong:
function foo($array) {
$success = true;
foreach ($array as $foo) {
if (/* something or other */) {
$success = false;
}
...
}
return $success;
}
You can return from a function at any point, including from within the foreach loop when you detect failure:
function do_process($array_vars){
foreach($array_vars as $array_var) {
// do the process
if (this step of the process failed)
return false;
}
// The foreach loop must have completed successfully
return true;
}
I would do this like this:
function do_process($array_vars){
$success = true;
foreach($array_vars as $array_var){
if (some condition appeared){ $success = false; }
}
return $success;
}
You can do it that way.
function process($array_items) {
foreach($array_items as $item) {
//processing to array goes here......
if($some_bottle_neck or $failure)
return false;
if($item == end($array_items))
return true;
}
}
Hopefully this is your solution.
精彩评论