i need create a structure where after check (1)if array is not empty, i (2)check the first value in array is bigger of my_value, if is not then check second value of array and so on. when the (2) is true then run my instruction and after i need exit to loop and go to the end of the script.
If after check all value in my array (2) is never true then i need return to the 'else' of (1)
'end of script' is the same for all and contain variables changed depending of the loop
I tryed with break and goto but not working .
what is the correct structure for this.
this structure is correct?
$myvalue='value';
cart_mem_rest = array('value1','value2','value3','value4');
if( sizeof( $cart_mem_rest) != 0 ){ //condition 1
foreach($cart_mem_rest as $kmem => $vmem_rest){
if ($vmem_rest > $myvalue){
//condition 2 : if first array value is bigger of $myvalue
//run my instruction and go to end script, if not then check
//other value , and other value .....
my instruction
Break;//go to end script
}
}
}else{
//here if conditions 1 or 2 are not verificated
if(condition is true ){
my instruction
}else{
my instruction
}
}
//end script
echo ' end script';
CodePudding user response:
I think it might be easier to set a variable to hold the result if the comparison succeeded inside the foreach.
In the foreach you can do the comparison if ($vmem_rest > $myvalue)
and when that is true set for example a variable $found = true
and break out of the loop.
Then you don't have to check if the array is not empty, and start with the foreach. If the array is empty, there is nothing for the foreach to process.
Now we can check if there was a match in the loop checking the value of $found
$myvalue = 'value';
$cart_mem_rest = array('value1', 'value2', 'value3', 'value4');
$found = false;
foreach ($cart_mem_rest as $kmem => $vmem_rest) {
if ($vmem_rest > $myvalue) {
// my instruction
$found = true;
break;
}
}
if (!$found) {
// my instruction
} else {
// my instruction
}
//end script
echo PHP_EOL . 'end script';