no idea how to ask this question... the problem is that I need to stop the loop from runing if if ($current[$id][$i]['item'] == '') is true, so whatever the script needs to do or in this case echo, don't get repeated 15 times.
If using exit; the whole page will stop to render, so, any ideas ?
Thanks in advance.
If the question is not clear enough don't hesitate to ask using the comments, I will more than happy to clarify any doubts.
$i=1;
while($i<=15) {
if ($current[$id][$i]['item'] == '') {
echo 'Done!.';
//do something
}
$a++;
}
use break
$i=1;
while($i<=15) {
if ($current[$id][$i]['item'] == '') {
echo 'Done!.';
break;
}
$i++; //<- that should probably be $i instead of $a?
}
How about using the break control structure?
You need to break. Also, your current loop is endless and will therefore time-out. Presumably you meant to increment $i, not $a.
$i=1;
while($i<=15) {
if ($current[$id][$i]['item'] == '') {
echo 'Done!.';
break; //<-- terminate loop
}
$a++; //<-- shouldn't this be $i++?
}
There is only 2 ways to break a loop... using exit; and break;....
break; is what you want it will exit the loop and continue execution, exit will end the script.
$i=1;
while($i<=15) {
if ($current[$id][$i]['item'] == '') {
echo 'Done!.';
break; // or you can make value of $i = 20;
}
$a++;
}
Related
I have a php script in which I have a if-else condition.. I want the script to end processing and start executing back from the top if the condition is not met... example :
<?php
$var = 2;
if($var != 1){
stop execution and go to the top and start executing again...
}else{
echo $var;
}
?>
How can I do that?
This can be achieved with the goto statement:
http://php.net/goto
If you want a infinite loop, then most simply put a infinite loop ... then break when you want to break
<?php
while(true){
$var = 2;
if($var != 1){
continue;
}else{
echo $var;
break;
}
}
?>
Is there something in php that can halt or let the script proceed if things are ok?
In my current scripts I do like this (for this example):
$fetch = false;
if($i == 10){
echo 'I is clear'
$fetch = true;
}
if($fetch){
//Do database work here
}
echo 'This should be seen no matter what the above';
Instead of the $fetch in there, can I do something else? I don't want to stop the entire script after that like what die() or exit does.
Here's an example that should help you:
<?php
function doLoop() {
for($i=0;$i<100;$i++) {
if($i != 50) {
continue; //It's not 50, skip it
}
//Otherwise
printf("Loop: $i");
}
}
function doBreak() {
for($i=0;$i<100;$i++) {
if($i != 49) {
continue; //It's not 49 yet, continue
} //Otherwise, break
printf("Loop: $i");
break;
}
}
doLoop();
doBreak();
?>
break; can be used to end a loop when a condition is met, while continue; can also be used to skip a certain value if a condition is not met. Using die(); would stop your whole script from executing, preventing it to call anything that comes after the die(); statement because that's how the execution of the scripts pretty much go, from the top to the end.
Let's take a look at the following code:
if ($a == 1) {
echo "this is stage 1";
}
else if ($a == 2) {
echo "this is stage 2";
}
else if ($a == 3) {
$a = 1;
// at this point I want something that restarts the if-else construct so
// that the output will be "this is stage 1"
}
I'm working on an if else construct at the moment and let's say that I have three stages and the if-else construct checks which stage I'm in.
Now it happens that some activities in stage 3 lead to a jump back to stage 1. Now I've already passed the code for stage one, which is why I want to somehow restart the if-else construct. Is there a way to do that? And even more important: Is there a better way to do what I want? Because my idea doesn't seem to be good practice.
You're right, it's bad practice.
You're asking for goto.
Example:
<?php
goto a;
echo 'Foo';
a:
echo 'Bar';
The above would never output 'Foo'
It's difficult to suggest the better method without seeing exactly what you're trying to do, but consider a switch.
switch ($a) {
case 3:
// Execute 3 stuff
// No break so it'll continue to 1
case 1:
// Execute 1 stuff
break // Don't go any further
case 2:
// 2 stuff
break;
}
That's probably not what you want either.
You may just want to abstract the code into functions and call them multiple times if necessary.
You can put an endless loop around your if and break out if you're done
while (1) {
if ($a == 1) {
echo "this is stage 1";
break;
}
else if ($a == 2) {
echo "this is stage 2";
break;
}
else if ($a == 3) {
$a = 1;
}
else {
break;
}
}
Maybe you want to look at Wikipedia - Finite-state machine and this question PHP state machine framework
The short answer is yes, there is a way, but the better answer is yes to your second question as well.
Put, at very least, the code that can get called from multiple locations in a function. For example,
function stageOneCode() {
//do stuff;
}
etc.. I would recommend a function for each stage, but it's hard to make recommendations without actually seeing what's being executed in the stages.
In any event, at the end of your stage three function, simply call your stage one function.
A recursive function is helpful for this (but maybe overkill if it will always revert back to 1)
function echo_stage($stage) {
if ($a == 1) {
return "this is stage 1";
}
else if ($a == 2) {
return "this is stage 2";
}
return echo_stage(1);
}
echo echo_stage(5);
Or:
switch ($number)
{
case 2 :
echo "this is stage 2";
break;
case 1:
default:
echo "this is stage 1"
}
use switch(). you can have a "default" case as well as specific cases.
A loop is what you are searching for:
// initialize $a
$a = 1;
// the while loop will return endless
while (true);
// if you want to break for any reason use the
// break statement:
// if ($whatever) {
// break;
// }
if ($a == 1) {
echo "this is stage 1";
}
else if ($a == 2) {
echo "this is stage 2";
}
else if ($a == 3) {
$a = 1;
// continue will go back to the head
// of the loop (step 1) early:
continue;
}
// don't forget to increment $a in every loop
$a++;
}
I just started learning php and I have to do something like this which I got it working but I just have a few questions I want to ask for alternate way of doing but eh first of all the br/ is suppose to be with <> but somehow if i do that the coding at the bottom will see it as a line break.
Anyways if questions are...
With the coding below the outcome will be 0-9 (without 5) but I have to set $zero=-1 if I put $zero=0 then the outcome would be 1-9 (without 5) is there a way I don't have to make $zero=-1 and still have the outcome of 0-9 (without 5)?
I realized I have to put $zero++ before the if and continue statement if I put it at the end of the script after echo "$zero" . "br/"; the script won't run as wanted. Is this how it is suppose to be or I just don't know the other way of doing it.
Thanks in advance for people replying ^_^
$squared = pow(3,2);
echo "\"3 squared is $squared:";
echo "br/";
$zero = -1;
while ($squared > $zero)
{
$zero++;
if ($zero == 5)
{
continue;
}
else if ($squared == $zero)
{
echo "$squared\"";
}
else
{
echo "$zero" . "br/";
}
}
Here it is (you were almost there :P )
$nr = 0;
while ($squared > $nr) {
if (5 == $nr) {
$nr++; // add this
continue;
} else if ($squared == $nr) {
echo "$squared\"";
} else {
echo "$nr" . "<br/>";
}
$nr++; // move to the bottom
}
PS: You're welcome #clement
Change your while loop to while ($squared >= $zero) and then set $zero = 0;
Should work!
I know there must be a nicer way to do this, but whenever I search "&&" i don't get good enough results...
<?php
if (empty($row[ContactName]) && empty($row[ContactEmail]) && empty($row[ContactPhone]) && empty($row[Website])){
echo "Not Provided";
}
else{
...do stuff...
}
?>
Thanks!
What is wrong with the original code?
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
Looks like fine code to me...
<?php
$i=1;
$ar=array('ContactName','ContactEmail','ContactPhone','Website')
foreach($ar as $a)
if (empty($row[$a]))
{
$i=0;
break; //to make code fast
}
if($i) //do stuff
else echo 'not provided';
?>
or if you really want to make your code extra small then change your column name in database
From To
ContactName Col1
ContactEmail Col2
ContactPhone Col3
Website Col4
and then do
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
else echo 'Not Provided';
?>
However it is not good to rename column as it will make your db somewhat less understandable.
As php functions have a lot of inconsistency, It's always a good idea using a library to make it more consistent.
put this function in that library:
function empty()
{
foreach(func_get_args() as $arg) if (empty($arg)) return false;
return true;
}
usage:
if (empty($row[ContactName], $row[ContactEmail], $row[ContactPhone], $row[Website])) {
echo "Not Provided";
}
you could make it as short as this if compactness was more important than readability :)
$required = array('ContactName', 'ContactEmail', 'ContactPhone', 'Website');
$ra = array_filter(array_intersect_key($row,array_flip($required)));
if(empty($ra)){
echo "Not Provided";
}
else{
//....
}
you can't put array_filter inside empty() or you get "Fatal error: Can't use function return value in write context"
1) array flip is turning your $required values into keys
2) array_intersect_key throws away any $row keys not found in $required
3) array_filter throws away any empty values
leaving you with a zero length array, which is empty. No need to worry about array lengths or loops
<?php
$flag = 1;
if (empty($row[ContactName])){
$flag = 0;
}
if (empty($row[ContactEmail])){
$flag = 0;
}
if (empty($row[ContactPhone])){
$flag = 0;
}
if (empty($row[Website])){
$flag = 0;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
?>
OR
$flag = 1;
$i=0;
$mustarray = array('ContactName','ContactName','ContactName','ContactName'); //or any number of fields that you want as mandatory
foreach($yourresult as $row){
if(empty($row[$mustarray [$i]])){
$flag = 0;
}
$i++;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
Do not play with making arrays and stuff just to make code look nicer.
As Tommy pointed
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
this code is nice, just need proper formatting like he pointed.
Making arrays and then launching loop will decrease performance
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
?>
this might look small, nice and "pro", but has more operations to give same results as a simple if instruction.
Not saying that it cant be done faster, i don't know php well, just remember about code executing speed.