I'm making a website for my clan.
I'd like to have a dynamic table of contents on the left.
E.G. If you click on the link "games" it should stop and print the other list. A list in a list.
I know, that sounds pretty strange, I think it'd be the best if I'll show you my code.
Here it is:
<div class="links">
<?php
$zeilen = file ('../inhaltsverzeichnis.txt');
foreach ($zeilen as $zeile)
{
if($zeile == 3)
{
$games = file ('games_inhaltsverzeichnis.txt');
foreach ($games as $game)
{
echo $game;
}
}
else
{
echo $zeile;
}
}
?>
I hope you know what I mean.
The break statement allows you to escape from the "nearest enclosing loop". If you add an argument (e.g. break 2;), you escape "the nearest two loops". Not absolutely sure how your code relates to the description of the problem (the title of the question), or where you would want the break statement - but that's what you need.
There are two columns in the database table "system". I have the systemId and want to get the mobileSystemId. But the variable $mobileSystemIds which I already defined as global is always empty.
EDIT: Now array_map doesn´t work. I always get my Exception output "Arrayfehler ArrayMap"
I have the following code :
$mobileSystemIds=array();
function getMobileSystemId($systemId)
{
global $mysqli;
global $mobileSystemIds;
$query="SELECT mobileSystemId FROM system WHERE systemId ='" .$systemId ."'";
if(!$result=$mysqli->query($query))
{
echo "Datenbankfehler DB-QUery";
exit(0);
}
if (!$mobileSystemId=$result->fetch_assoc())
{
echo "Datenbankfehler DB-Fetch";
exit(0);
}
$mobileSystemId=$mobileSystemId["mobileSystemId"];
echo "mobile System ID: " .$mobileSystemId ."<br />";
return $mobileSystemId;
}
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
In this case, using a return in your function would be much cleaner.
Nothing to do with your problem, but is your $systemId var trusted ? (To prevent SQL injection).
Update:
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
ought to read (just checked; it works for me):
$mobileSystemIds = array_map('getMobileSystemId', $systemsList);
if (empty($mobileSystemIds))
{
if (empty($systemsList) || !(is_array($systemsList)))
echo "OK: no mobile IDs, but no systems either";
else
echo "THIS now is strange :-(";
}
else
{
echo "Alles OK";
var_dump($mobileSystemIds);
}
I tried this by returning a dummy value based on input; if it does not work for you, there must be something strange in the database.
(Update: the text below refers to your original code, which did not use array mapping)
Your code ought to be working as it is. You put several $mobileSystemId 's into a single $mobileSystemId.
It works: I tested with a simpler code, removing the DB calls but leaving your code, and spelling, untouched.
So, the error must be elsewhere. I would guess that this code is included into something else, and:
the $mobileSystemIds = array(); declaration gets executed more than once, thereby losing all its data;
the $mobileSystemIds = array(); declaration is itself included in a more local scope and you read it from outside, reading an empty value or a totally different value.
Try replacing the first part of your code with:
GLOBAL $mobileSystemsIds;
if (defined($mobileSystemsIds))
trigger_error("mobileSystemsId defined more than once", E_USER_ERROR);
else
$mobileSystemsIds = array();
and also, in the function body:
if (!defined($mobileSystemsId))
trigger_error("mobileSystemsId should have been defined", E_USER_ERROR);
Is there any command in PHP to stop executing the current or parent if statement, same as break or break(1) for switch/loop. For example
$arr=array('a','b');
foreach($arr as $val)
{
break;
echo "test";
}
echo "finish";
in the above code PHP will not do echo "test"; and will go to echo "finish";
I need this for if
$a="test";
if("test"==$a)
{
break;
echo "yes"; // I don't want this line or lines after to be executed, without using another if
}
echo "finish";
I want to break the if statement above and stop executing echo "yes"; or such code which is no longer necessary to be executed, there may be or may not be an additional condition, is there way to do this?
Update: Just 2 years after posting this question, I grew up, I learnt how code can be written in small chunks, why nested if's can be a code smell and how to avoid such problems in the first place by writing manageable, small functions.
Sometimes, when developing these "fancy" things are required. If we can break an if, a lot of nested ifs won't be necessary, making the code much more clean and aesthetic.
This sample code illustrates that in certain situations a breaked if can be much more suitable than a lot of ugly nested ifs.
Ugly code
if(process_x()) {
/* do a lot of other things */
if(process_y()) {
/* do a lot of other things */
if(process_z()) {
/* do a lot of other things */
/* SUCCESS */
}
else {
clean_all_processes();
}
}
else {
clean_all_processes();
}
}
else {
clean_all_processes();
}
Good looking code
do {
if( !process_x() )
{ clean_all_processes(); break; }
/* do a lot of other things */
if( !process_y() )
{ clean_all_processes(); break; }
/* do a lot of other things */
if( !process_z() )
{ clean_all_processes(); break; }
/* do a lot of other things */
/* SUCCESS */
} while (0);
As #NiematojakTomasz says, the use of goto is an alternative, the bad thing about this is you always need to define the label (point target).
Encapsulate your code in a function. You can stop executing a function with return at any time.
proper way to do this :
try{
if( !process_x() ){
throw new Exception('process_x failed');
}
/* do a lot of other things */
if( !process_y() ){
throw new Exception('process_y failed');
}
/* do a lot of other things */
if( !process_z() ){
throw new Exception('process_z failed');
}
/* do a lot of other things */
/* SUCCESS */
}catch(Exception $ex){
clean_all_processes();
}
After reading some of the comments, I realized that exception handling doesn't always makes sense for normal flow control. For normal control flow it is better to use "If else":
try{
if( process_x() && process_y() && process_z() ) {
// all processes successful
// do something
} else {
//one of the processes failed
clean_all_processes();
}
}catch(Exception ex){
// one of the processes raised an exception
clean_all_processes();
}
You can also save the process return values in variables and then check in the failure/exception blocks which process has failed.
Because you can break out of a do/while loop, let us "do" one round. With a while(false) at the end, the condition is never true and will not repeat, again.
do
{
$subjectText = trim(filter_input(INPUT_POST, 'subject'));
if(!$subjectText)
{
$smallInfo = 'Please give a subject.';
break;
}
$messageText = trim(filter_input(INPUT_POST, 'message'));
if(!$messageText)
{
$smallInfo = 'Please supply a message.';
break;
}
} while(false);
goto:
The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break...
There exist command: goto
if(smth) {
.....
.....
.....
.....
.....
goto My123;
.....
.....
}
My123:
....your code here....
BUT REMEMBER! goto should not be ever used anywhere in real-world scripts, as it is a sign of poor code.
You could use a do-while(false):
<?php
do if ($foo)
{
// Do something first...
// Shall we continue with this block, or exit now?
if ($abort_if_block) break;
// Continue doing something...
} while (false);
?>
as described in http://php.net/manual/en/control-structures.if.php#90073
No, there is no way to "break" an if block like you would inside loops.:(
So turn your test into a switch !
I wonder why nobody encouraged you to use switch statement since (even if you haven't to many test cases)
Do you think it's too verbose?
I would definitely go for it here
switch($a){
case 'test':
# do stuff here ...
if(/* Reason why you may break */){
break; # this will prevent executing "echo 'yes';" statement
}
echo 'yes'; # ...
break; # As one may already know, we might always have to break at the end of case to prevent executing following cases instructions.
# default:
# something else here ..
# break;
}
To me Exceptions are meant to raise errors and not really to control execution flaw.
If the break behaviour you are trying to set is not about unexpected error(s), Exception handling is not the right solution here :/.
$a = 1;
switch($a) {
case "1":
if ($condition1){
break;
}
if ($condition2){
break;
}
if ($condition3){
break;
}
}
In this way I got what I want. I use a switch only has a definite case and then use break in case to choose if condition. The reason why I use the break : condition1 and condition2 may both satisfy, in that situation only condition1 is applied .IF is selective according the order.
I had the same problem. A solution is to pile if.
The first example is simplistic but...
$a="test";
if("test"==$a)
{
do something
//break; We remove from your example
if(comparison) {
echo "yes";
}
}
echo "finish";
Or, you can use goto.
$a="test";
if("test"==$a)
{
do something
goto the_end_of_your_func;
echo "yes";
}
the_end_of_your_func:
echo "finish";
No.
But how about:
$a="test";
if("test"==$a)
{
if ($someOtherCondition)
{
echo "yes";
}
}
echo "finish";
Just move the code that is not supposed to be executed to else/elseif branch. I don't really see why would you want to do what you're trying to do.
The simple answer is that no, there isn't a way to break from an if statement without completely stopping the execution (via exit). Other solutions won't work for me because I can't change the structure of the if statement, since I'm injecting code into a plugin, like so:
if ( condition ) {
// Code and variables I want to use
// Code I have control over
// Code I don't want to run
}
// More code I want to use
Answering to your question whether that is achievable or not, then yes that is achievable using "goto" operator of php.
But ethically, its not a good practice to use "goto" and of there is any need to use goto then this means that code need to be reconstructed such that requirement of goto can be removed.
According to the sample code you posted above, it can be clearly seen that the code can be reconstructed and the code that is no more required can be either deleted or commented (if possibility is there for use in future).
$arr=array('test','go for it');
$a='test';
foreach($arr as $val){
$output = 'test';
if($val === $a) $output = "";
echo $output;
}
echo "finish";
combining your statements, i think this would give you your wished result.
clean and simple, without having too much statements.
for the ugly and good looking code, my recomandation would be:
function myfunction(){
if( !process_x() || !process_y() || !process_z()) {
clean_all_processes();
return;
}
/*do all the stuff you need to do*/
}
somewhere in your normal code
myfunction();
i have a simple solution without lot of changes.
the initial statement is
I want to break the if statement above and stop executing echo "yes"; or such code which is no longer necessary to be executed, there may be or may not be an additional condition, is there way to do this?
So it seems simple. try code like this:
$a="test";
if("test"==$a)
{
if (1==0){
echo "yes"; // this line while never be executed.
// and can be reexecuted simply by changing if (1==0) to if (1==1)
}
}
echo "finish";
if you want to try without this code, it's simple. and you can back when you want. another solution is comment blocks.
or simply thinking and try in another separated code and copy paste only the result in your final code.
and if a code is no longer nescessary, in your case, the result can be
$a="test";
echo "finish";
with this code, the original statement is completely respected
and more readable!
The simple solution is to comment it out.
$a="test";
if("test"==$a)
{
//echo "yes"; //no longer needed - 7/7/2014 - updateded bla bla to do foo
}
The added benefit is your not changing your original code and you can date it, initial it and put a reason why.
What about using ternary operator?
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
?>
Which is identical to this if/else statement:
<?php
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>
To completely stop the rest of the script from running you can just do
exit; //In place of break. The rest of the code will not execute
I'm late to the party but I wanted to contribute. I'm surprised that nobody suggested exit(). It's good for testing. I use it all the time and works like charm.
$a ='';
$b ='';
if($a == $b){
echo 'Clark Kent is Superman';
exit();
echo 'Clark Kent was never Superman';
}
The code will stop at exit() and everything after will not run.
Result
Clark Kent is Superman
It works with foreach() and while() as well. It works anywhere you place it really.
foreach($arr as $val)
{
exit();
echo "test";
}
echo "finish";
Result
nothing gets printed here.
Use it with a forloop()
for ($x = 2; $x < 12; $x++) {
echo "Gru has $x minions <br>";
if($x == 4){
exit();
}
}
Result
Gru has 2 minions
Gru has 3 minions
Gru has 4 minions
In a normal case scenario
$a ='Make hot chocolate great again!';
echo $a;
exit();
$b = 'I eat chocolate and make Charlie at the Factory pay for it.';
Result
Make hot chocolate great again!
$a="test";
if("test"!=$a)
{
echo "yes";
}
else
{
echo "finish";
}
When you want to omit the remaining of a loop you write a break statement.
Is there something that you can write to omit the remaining of an included file (but not terminate the rest of the app like when using die or exit)?
You can use a return statement to exit an included file, and optionally return a value.
Example:
<?php
// file1.php:
$value = include('file2.php');
echo $value;
Which includes:
<?php
// file2.php:
if($_REQUEST['something'] == 'something else')
return 'Something else';
//do some stuff if _REQUEST['something'] != 'something else'
return 'something';
Obviously a useless example, but, it demonstrates the use of return to eit an include()ed file.
you could split your include into two separate files, then require the two as necessary instead of just one, or possibly just require the one and have that one require the second as necessary.
I have this code:
$layout_template = template_get("Layout");
$output_template = template_get("Homepage");
$box = box("Test","Test","Test");
eval("\$output = \"$layout_template\";");
echo $output;
In the $template_layout variable is a call for the
variable $output_template, so then the script moves onto the $output_template variable
But it doesn't go any further, inside the $output_template is a call to the variable $box, but it doesn't go any further than one level
I would never want nested eval(), and especially not in any recursive logic. Bad news. Use PHP's Include instead. IIRC eval() creates a new execution context, with overhead whereas include() doesn't.
If you have buffers such as:
<h1><?php echo $myCMS['title']; ?></h1>
I sometimes have files like Index.tpl such as above that access an associative array like this, then you just do in your class:
<?php
class TemplateEngine {
...
public function setvar($name, $val)
{
$this->varTable[$name]=make_safe($val);
}
....
/* Get contents of file through include() into a variable */
public function render( $moreVars )
{
flush();
ob_start();
include('file.php');
$contents = ob_get_clean();
/* $contents contains an eval()-like processed string */
...
Checkout ob_start() and other output buffer controls
If you do use eval() or any kind of user data inclusion, be super safe about sanitizing inputs for bad code.
It looks like you are writing a combined widget/template system of some kind. Write your widgets (views) as classes and allow them to be used in existing template systems. Keep things generic with $myWidget->render($model) and so on.
I saw this on the PHP doc-user-comments-thingy and it seems like a bad idea:
<?php
$var = 'dynamic content';
echo eval('?>' . file_get_contents('template.phtml') . '<?');
?>
Perhaps someone can enlighten me on that one :P