What does for(;;) do? - php

I have to maintain a code, and came up with this:
for (;;) {
//code
}
What would it do? I couldn't find documentation about it.
In a hunch I think it runs only once... but that would be useless...

it is an infinite loop, similar in function as:
while(true)
{
}

Your code sample is an infinite loop. To terminate, the omitted code (//code) must exit the loop or the entire PHP script.

It's a for loop without initialization parameters, no breaking conditions and no increments/decrements/whatever on each iteration - think of it like for (nothing; nothing; nothing).
Unless you break it from the inside, it's going to run forever.

For embedded code it is the main loop that does all the other sub process in a super loop scheme.

Related

Function calls itself, is this possible?

I've been looking around the internet trying to learn more about sanitization an validation in PHP and it's the second time I run into this type of function that I have some trouble understanding how this foreach statement works.
This is the code, taken from here:
function sanitize($input) {
if (is_array($input)) {
foreach($input as $var=>$val) {
$output[$var] = sanitize($val);
}
}
else {
if (get_magic_quotes_gpc()) {
$input = stripslashes($input);
}
$input = cleanInput($input);
$output = mysql_real_escape_string($input);
}
return $output;
}
So my doubt lies in the foreach statement if the $input is_array, where each index of the array is passed through the function that is being created. For a novice programmer like myself I'm not sure how you can call something halfway within it's creation.
I've done some passing around munching the idea and think I've reached an answer, but I'm not sure if that's the case and that's why I'm asking this question, both for confirmation and guidance to some literature that might help me grasp this type of "use".
So I'm thinking that when the function is called sanitize($someArray); it will evaluate to true on the if statement and run the foreach. On each of the indexes when it runs the sanitize($val); it will jump to the else statement and run the "single value" instructions. Unless of course $input is an array of arrays, in which case it would repeat the first step until each item is sanitized in each array.
My doubt appears, because this is what I see too some extent:
function sanitize($input) {
if(foo){sanitize($input->i);}
else {...}
}
I instinctively expect an infinite loop.
Does this make sense? Is it a mistake made in the code? Are there any chances of it running indefinitely?
The function isn't called until after it is created. And it only operates on a smaller piece of the original input. Eventually something that is not an array will be reached, and the levels of recursion will fall away.
Nope, it is recursive, but will not run till death do us part.
You have one instance of the function sanitize (sanitize.1). That received an array. As it is an array, indeed, it will call on a function sanitize(lets call it Sanitize.2, for clarity). That runs next to sanitize.1.
However, in sanitize.1 you only pass a single value to the function. So indeed, it jumps to the else part of the function. Clean the variable. Return the sanitized input, and disappear again. At that time, sanitize.1 steps to the next element in the array, and runs the whole thing again.
In your situation where each element of the passed array is also an array, it still works: each sub array is treated in the same way and you get sanitize.1 calling sanitize.2 which in turn calls sanitize.3. That you can do indefinately. As computers are real good of keeping track of what they are doing, they can do this, where you and I on a piece of paper would make a big mess of it ;D

While Loop - PHP

I've got a few while loops in my PHP code that look somewhat like this:
qry_myquery = "SELECT * FROM table WHERE value = '$value' ";
$rs_myquery = mysql_query($qry_myquery) or die(mysql_error());
while($row = mysql_fetch_assoc($rs_myquery)){
if($row[$entryType] > 0){
$entryPointNumber = $row[$entryType];
}else {
$data["FatalError2"] = "Error!";
die();
}
} //END: While loop - entries from AJAX legal.
My question - is there anything wrong with writing while loops in this way? Will they continue to run indefinitely and suck memory/unneeded processing power? Am I supposed to close them off somehow after I'm done with them?
is there anything wrong with writing while loops in this way?
no
Will they continue to run indefinitely and suck memory/unneeded processing power?
no, it runs as long as the condition is true, in your case, when there are no more rows, the loop will stop
Am I supposed to close them off somehow after I'm done with them?
no (but maybe i didnt understand what you are asking here)
The WHILE loop seems to be fine and the loop wont run indefinitely.
But I see one issue with the code, which is the die() statement.
By calling the die(), you are not doing a clean exit in the code.
What I mean is you are not closing the database connect.

Why does for(;;) work?

I was looking through some code at work and found something I've not encountered before:
for (; ;)
{
// Some code here
break;
}
We call the function that contains this all the time, I only recently got in there to see how it works. Why does this work and is it documented somewhere?
It seems as though a while loop would have been more appropriate in this instance...
It's essentially the same as while(true). It doesn't have any initialisation, doesn't change anything between iterations, and in the absence of anything to make it false the condition is assumed to be true.
It's an infinite loop.
Normally you would have something like:
for ($i=0; $i<10; $i=$i+1)
But you can omit any of the parts.
These are all valid:
for ($i=0; ; $i=$i+1)
for (; $i<10; $i=$i+1)
for (; $i<10;)
However, if you omit the second part, there will be no condition for exiting the loop. This can be used if you do not know how many times you want to run the loop. You can use a break instruction to exit the loop in that case
for (;;)
{
// some code
if (some condition)
break;
}
Note that if you do not put a break the page will just get stuck and run indefinitely
The first blank statement is executed at the beginning.
The second blank expression (which determines whether you exit the loop or not) evaluates to TRUE implicitly:
http://php.net/manual/en/control-structures.for.php
The third blank statement executes after each iteration.
So any condition that kicks out of the loop will need to be in the loop itself.

"Continue" alternative that doesn't skip but repeats the loop

I'm using PHP's foreach(), Sometimes when the inner code doesn't do what i want, I'd like to re-try the same level instead of continuing to the next one.
Is that possible?
Example:
foreach($pics AS $pic){
if(!upload($pic)){
again; // something like this
}
}
No but you can put a while loop inside your loop, this has equivalent behaviour as what you desire above. However you should modify it to use a counter and stop after X many retries to prevent infinite looping.
foreach($pics AS $pic){
while(!upload($pic));
}
You will need to surround your if with another loop which loops a certain number of times (your maximum retry count), or until you manually break out of it when your code succeeds.
You could use a goto I suppose, but that is generally frowned upon, and would do the same thing as an inner loop anyway.
function dosomething() {
foreach($pics AS $pic){
if(!upload($pic)){
break;
}
}
$success = true;
}
$success=false;
while( !$success ) dosomething();
While this in theory should work.
I would say absolutely bad programming practice, as you have a good chance of a never ending loop.

for each ... break

I feel dirty every time I "break" out of a for-each construct (PHP/Javascript)
So something like this:
// Javascript example
for (object in objectList)
{
if (object.test == true)
{
//do some process on object
break;
}
}
For large objectLists I would go through the hassle building a more elegant solution. But for small lists there is no noticeable performance issue and hence "why not?" It's quick and more importantly easy to understand and follow.
But it just "feels wrong". Kind of like a goto statement.
How do you handle this kind of situation?
I use a break. It's a perfectly cromulent solution.
It's quick and more importantly easy to understand and follow.
Don't feel bad about break. Goto is frowned upon because it's quick and more importantly not easy to understand and follow.
See, the break doesn't bug me at all. Programming is built on goto, and for-break - like all control structures - is merely a special-purpose form of goto meant to improve the readability of your code. Don't ever feel bad about writing readable code!
Now, I do feel dirty about direct comparisons to true, especially when using the type-converting equality operator... Oh yeah. What you've written - if (object.test == true) - is equivalent to writing if (object.test), but requires more thought. If you really want that comparison to only succeed if object.test is both a boolean value and true, then you'd use the strict equality operator (===)... Otherwise, skip it.
For small lists, there's no issue with doing this.
As you mention, you may want to think about a more 'elegant' solution for large lists (especially lists with unknown sizes).
Sometimes it feels wrong, but it's all right. You'll learn to love break in time.
Like you said ""why not?" It's quick and more importantly easy to understand and follow."
Why feel dirty, I see nothing wrong with this.
I think is is easier to read and hence easier to maintain.
It is meant to be like it. Break is designed to jump out of a loop. If you have found what you need in a loop why keep the loop going?
Breaks and continues are not gotos. They are there for a reason. As soon as you're done with a loop structure, get out of the loop.
Now, what I would avoid is very, very deep nesting (a.k.a. the arrowhead design anti-pattern).
if (someCondition)
{
for (thing in collection)
{
if (someOtherCondition)
{
break;
}
}
}
If you are going to do a break, then make sure that you've structure your code so that it's only ever one level deep. Use function calls to keep the iteration as shallow as possible.
if (someCondition)
{
loopThroughCollection(collection);
}
function loopThroughCollection(collection)
{
for (thing in collection)
{
if (someOtherCondition)
{
doSomethingToObject(thing);
break;
}
}
}
function doSomethingToObject(thing)
{
// etc.
}
I really don't see anythign wrong with breaking out of a for loop. Unless you have some sort of hash table, dictionary where you have some sort of key to obtain a value there really is no other way.
I'd use a break statement.
In general there is nothing wrong with the break statement. However your code can become a problem if blocks like these appear in different places of your code base. In this case the break statements are code small for duplicated code.
You can easily extract the search into a reusable function:
function findFirst(objectList, test)
{
for (var key in objectList) {
var value = objectList[key];
if (test(value)) return value;
}
return null;
}
var first = findFirst(objectList, function(object) {
return object.test == true;
}
if (first) {
//do some process on object
}
If you always process the found element in some way you can simplify your code further:
function processFirstMatch(objectList, test, processor) {
var first = findFirst(objectList, test);
if (first) processor(first);
}
processFirst(
objectList,
function(object) {
return object.test == true;
},
function(object) {
//do some process on object
}
}
So you can use the power of the functional features in JavaScript to make your original code much more expressive. As a side effect this will push the break statement out of your regular code base into a helper function.
Perhaps I'm misunderstanding your use-case, but why break at all? I'm assuming you're expecting the test to be true for at most one element in the list?
If there's no performance issue and you want to clean up the code you could always skip the test and the break.
for (object in objectList)
{
//do some process on object
}
That way if you do need to do the process on more than one element your code won't break (pun intended).
Use a
Object object;
int index = 0;
do
{
object = objectList[index];
index++;
}
while (object.test == false)
if breaking from a for loop makes you feel uneasy.
My preference is to simply use a break. It's quick and typically doesn't complicate things.
If you use a for, while, or do while loop, you can use a variable to determine whether or not to continue:
for ($i = 0, $c = true; ($i < 10) && $c; $i++) {
// do stuff
if ($condition) {
$c= false;
}
}
The only way to break from a foreach loop is to break or return.

Categories