Break out of while and skip the following loops - php

I am looking for an element in multiple while loops, but if the element is found, I don't need to check the following while loops. How can I achieve something like this?
while(something) {
if (this = key) {
// break this loop and skip the next ones. Otherwise proceed to next.
}
}
while(somethingelse) {
if (this = key) {
// break this loop and skip the next ones. Otherwise proceed to next.
}
}
while(somethingthird) {
if (this = key) {
// break this loop and skip the next ones. Otherwise stop looking.
}
}

Use a variable (boolean) that knows if your condition was checked in the previous while, like this:
$breakAll = false; //default false
while(something) {
if (this = key) {
// break this loop and skip the next ones. Otherwise proceed to next.
$breakAll = true; //now break all whiles
}
}
while(somethingelse && !breakAll) {
if (this = key) {
// break this loop and skip the next ones. Otherwise proceed to next.
$breakAll = true; //same here
}
}
while(somethingthird && !breakAll) {
if (this = key) {
// break this loop and skip the next ones. Otherwise stop looking.
}
}

Refactor the while loops to a function and return when the element is found
function doSomething() {
while(something) {
if (this == key) {
return;
}
}
while(somethingelse) {
if (this == key) {
return;
}
}
while(somethingthird) {
if (this == key) {
return;
}
}
}

Use a function
function findSpecificElement($element)
{
while ($something) {
if ($something == $element) {
return $something;
}
}
while ($something) {
if ($something == $element) {
return $something;
}
}
...
}

More correct to use php operator: continue, see:
http://php.net/manual/en/control-structures.continue.php
Example:
while (list($key, $value) = each($arr)) {
if (!($key % 2)) { // skip even members
continue;
}
do_something_odd($value);
}
Operator: break; - break the loop
http://php.net/manual/en/control-structures.break.php
while(something) {
if (this == key) {
break;
}
}

goto can be used in a situation like this to jump over the while loops that should not be run.
while(something) {
if (this = key) {
goto yourDoom; // Breaks out of loop and goes to label "yourDoom"
}
}
while(somethingelse) {
if (this = key) {
goto yourDoom; // Breaks out of loop and goes to label "yourDoom"
}
}
while(somethingthird) {
if (this = key) {
goto yourDoom; // Breaks out of loop and goes to label "yourDoom"
}
}
yourDoom: // This is a label that you can go to
// Do something

Related

While Loop Through An Array

Creating a block builder that loops through blocks pulled form database in order.
if( loop_blocks()) {
while( loop_blocks()) {
if( have_block('standard-content-block')) {
echo 'standard-content-block';
}
elseif( have_block('executive-intro-block')) {
echo 'executive intro block';
}
}
}
My function loop_blocks pulls the blocks from the database in order and set the array as a global variable:
function loop_blocks() {
global $db;
$page_id = get_page_id();
$GLOBALS['loop_position'] = 0;
$loop_position = $GLOBALS['loop_position'];
$stm = $db->prepare("SELECT * FROM page_blocks WHERE page_id = :id ORDER BY `block_order` ASC");
$stm->execute(array(':id' => $page_id));
$res = $stm->fetchAll();
$GLOBALS['block_loop'] = $res;
if(!$res) {
return false;
} elseif(!$GLOBALS['block_loop'][$loop_position]) {
return false;
} else {
return true;
}
}
The function have_block gets the current loop position and determines whether the name as determined, exists in the array and increases the loop position:
function have_block($block_name) {
$loop_position = $GLOBALS['loop_position'];
if(!$GLOBALS['block_loop'][$loop_position]) {
return false;
} elseif(!$GLOBALS['block_loop'][$loop_position][block_name] = $block_name) {
return false;
} else {
$GLOBALS['loop_position'] = $loop_position+1;
return true;
}
}
This returns an infinite loop however and I can't figure out a way to move the while loop onto the next step?
EDIT I'm using a while loop because the function have_block will set-up a global variable for the current block id. This will then be used within a function called the_element. Such as:
if( loop_blocks()) {
while( loop_blocks()) {
if( have_block('standard-content-block')) {
the_element('heading');
}
}
}
If I don't use the function have_block to set this up, then I'd need to pass the block id from the foreach loop into every element as a second argument.
I fixed this by, as #Jim, noted I was re-setting the loop_position within loop_blocks() which was why the while loop was repeating infinitely. It was then a simple case of an error when typing:
} elseif(!$GLOBALS['block_loop'][$loop_position][block_name] = $block_name) {
return false;
Should have been:
} elseif($GLOBALS['block_loop'][$loop_position][block_name] != $block_name) {
return false;
Note that I had the exclamation point in the incorrect place.
This now works perfectly as I need.

Is it possible to create a for loop inside an if condition?

I need to check if some text areas are set, but there might be a lot of them. I want to check if every single one of them is set inside an if statement with a for loop.
if(//for loop here checking isset($_POST['item'.$i]) )
You could do this:
// Assume all set
$allSet = true;
// Check however many you need
for($i=0;$i<10;$i++) {
if (!isset($_POST['item'.$i])) {
$allSet=false; // If anything is not set, flag it and bail out.
break;
}
}
if ($allSet) {
//do stuff
} else {
// do other stuff
}
If you've only a few, or they're not sequential there's no need for a loop. You can just do:
if (isset($_POST['a'], $_POST['d'], $_POST['k']....)) {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
try using this:
$post=$_POST;
foreach($post as $key=>$value){
if (isset($value) && $value !="") {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
You can try:
<?php
$isset = true;
$itemCount = 10;
for($i = 0; $i < $itemCount && $isset; $i++){
$isset = isset($_POST['item'.$i]);
}
if ($isset){
//All the items are set
} else {
//Some items are not set
}
I'm surprised that after three answers, there isn't a correct one. It should be:
$success = true;
for($i = 0; $i < 10; $i++)
{
if (!isset($_POST['item'.$i]))
{
$success = false;
break;
}
}
if ($success)
{
... do something ...
}
Many variation are possible, but you can really break after one positive.
Yes, one may have a loop within an if-condtional. You may use a for-loop or you may find it more convenient to use a foreach-loop, as follows:
<?php
if (isset($_POST) && $_POST != NULL ){
foreach ($_POST as $key => $value) {
// perform validation of each item
}
}
?>
The if conditional basically tests that a form was submitted. It does not prevent an empty form from being submitted, which means that any required data must be checked to verify that the user provided the information. Note that $key bears the name of each field as the loop iterates.

foreach function only show last value

when i wanna get all value to check with current user ip it just check last ip with current user , i don't know why before values doesnt check.
i fill IPs in a textarea like this : 176.227.213.74,176.227.213.78
elseif($maintenance_for == '2') {
$get_ips = $options['ips'];
$explode_ips = explode(',',$get_ips);
foreach ($explode_ips as $ips) {
if($ips == $_SERVER["REMOTE_ADDR"]){
$maintenance_mode = true;
}
else {
$maintenance_mode = false;
}
}
}
If you found the right value, you wan't to BREAK out of the foreach loop
$get_ips = $options['ips'];
$explode_ips = explode(',', $get_ips);
foreach($explode_ips as $ips) {
if ($ips == $_SERVER["REMOTE_ADDR"]) {
$maintenance_mode = true;
break; // If the IP is right, BREAK out of the foreach, leaving $maintenance_mode to true
} else {
$maintenance_mode = false;
}
}
yes, you will always override it. Its better to set a default and only set it once:
(Edit: added #Mathlight's answer, the break, in my solution as he suggested)
$maintenance_mode = false;
foreach ($explode_ips as $ips) {
if($ips == $_SERVER["REMOTE_ADDR"]){
$maintenance_mode = true;
break;
}
}
EDIT : another solution for the record, for the points of a oneliner
$maintenance_mode = in_array($_SERVER["REMOTE_ADDR"], $explode_ips);

How do you use break in php 5.4 after it lost its ability to receive variables?

The php manual states under 'Changelog for break':
5.4.0 Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument.
I have a function that copies a table with a tree structure to another table.
After copying each record, the function tests a relation to see if that record has more child records in the next "level" of the tree.
If child records are found, this same function is executed for each child record using a foreach() loop. If they also have child records, the process is repeated, etc. etc.
So the number of "branches" and "levels" in the table will determine how many foreach() loops will be executed. Since the user creates the records, I have no control over the number of "branches" and "levels" in the table.
If break cannot receive a variable any more (I cannot run "branch" and "level" counters any more) - how do you break out of ALL loops if an error occurs?
Scaled down example:
public function copyTreeModels($row, $id)
{
try
{
/* copy current record. */
$status == 'ok';
/* loop to this same function if $status == 'ok' and hasChildren */
if($status == 'ok')
{
If ($row['hasChildren'] == 'yes') // check relation
{
foreach($row['children'] as $child)
{
$this->copyTreeModels($child, $id);
}
}
}
else
{
// break;
throw new CDbException($message);
}
}
catch(CDbException $e)
{
$message .= $e->getMessage();
}
return($message);
}
Don't put try in the recursive function. You need a wrapper function around the whole thing that establishes the condition handler:
public function copyTreeModels($row, $id) {
try {
$this->copytreeModelsRecurse($row, $id);
}
catch(CDbException $e)
{
$message .= $e->getMessage();
}
return($message);
}
copyTreeModelsRecurse would then be your copyTreeModels function, but without the try/catch blocks.
The only thing I can think of is to set a variable which determines whether or not to break all.
An example (untested) is
$break_all = false;
foreach($values as $val) {
foreach($val as $val1) {
foreach($val1 as $val2) {
if($val2 == "xyz") {
$break_all = true;
}
if($break_all) break;
}
if($break_all) break;
}
if($break_all) break;
}
I'll agree with the fact it's not a pretty solution however.
Edit:
An alternative suggestion if the amount of nested loops to break; from is a variable amount is setting a counter and decrementing the break counter for each break, and only breaking if it is greater than 0:
$break_count = 0;
foreach($values as $val) {
foreach($val as $val1) {
foreach($val1 as $val2) {
if($val2 == "xyz") {
$break_count = 3;
}
if($break_count > 0) { $break_count--; break; }
}
if($break_count > 0) { $break_count--; break; }
}
if($break_count > 0) { $break_count--; break; }
}

Skip parent if using PHP

Not sure if this is even possible, but the basic idea of the code is as follows:
if(isset($_POST['submit'])) {
if($_POST['field'] == 0) {
// do not process the code in the if statement
}
// code to process if the above validation criteria is not met
}
I basically want to try and keep it as simple as possible without lots of if's everywhere, just the quick validation statements at the top, and if none of those if statements are triggered, it will process the code to update the database etc.
I have tried the continue statement function with no joy, I believe that only works with loops.
Thanks!
if(isset($_POST['submit']) && $_POST['field'] != 0) {
}
As a function
function testCondition() {
return isset($_POST['submit']) &&
$_POST['field'] != 0;
}
if (testCondition()) { ... }
You could put all of this in a function and then call 'return' from the inside 'if':
if(isset($_POST['submit']) && validate_form())
{
...
}
function validate_form()
{
if($_POST['field'] == 0) {
return false;
}
if(another check that fails) {
return false;
}
...
return true;
}
To accomplish this as you originally desired, you need to use the break statement. From the PHP manual:
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
/* Using the optional argument. */
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}

Categories