Countdown from 100 to 0 with no assignations in PHP - php

I'm having a problem figuring out an exercise my boss gave me as personal enrichment of knowledge sort of. Unfortunately I have been looking for a glimpse of answer everywhere on the web with no success and I'm now turning to you fellow programmers.
What he asked me to do is make a simple countdown from 100 to 0 (it can be displayed all at once). Easy enough so far eh? Just make a simple for loop or a while even. The problem here is that he asks that there are no assignations in the code, ex: $[var]=[value].
How can one even make a loop with no assignations? Since $i--; is the equivalent to $i = $i - 1; how can we count down?
I'm baffled by this problem which I can't resolve, I really want to find the answer as I am very curious on how this can be done.
Help is kindly appreciated.
Edit
Take note that this problem is kind of a 2 part where as the first part is to make it work 100 to 0, and in the second part x to 0 where x is inputted by the user

I will give you some hints, writing the exact code is an exercise for you.
No assignments, so you must have some type that can hold multiple values. Primitive types like integers cannot be used directly here, think of arrays.
Now, you cannot use variables, so using a loop and then printing the values is disallowed. Use one of the many ways to print an array (or the result of operating on an array).
The range() function does not accept a negative step value, you need to reverse the numbers.

My guess would be that your boss is trying to encourage you towards recursion rather than iteration. Recursion, as a technique, works extremely well for certain problems, and is an excellent tool to have in your armoury as a programmer.
Without giving everything away, try experimenting with defining a function that takes an argument - the "countdown" number -- and then calls itself in some way. You'll also need to separately kick it off by calling it once you've defined it.
Bear in mind that recursion must have some kind of termination defined, otherwise things can go very wrong. Here's an example of something going very wrong to get you started: :D
<?php
function infinity() {
print "Whoah.";
infinity();
}
infinity();

Related

Some Tips to properly number SQL queries

As an Amateur PHP Developer I often have this problem of mixing sequences and variables.
SHORT :
So what would be the tips to keep in mind when writing a webpage that has many SQL queries.
I have thought of an idea of making a function but I am not sure if that would be of any good.
LONG:
The problem is I have a PHP page that has many sql queries which are followed by result, row , row_number, and die() if result unsuccessful after running the query.
I number them as sql1, result1, row1, error1, mysqlouput1 and sql2.... and so on..
When I add one more query after five or six days I have to go through the whole code to find out which was the last sequence used and take the next one, many times i just use the same and it creates strange problems.
The same problem with variables, as the same page is loading again and again with different POST and GET ids keeping track of variables is just too messy.
So what would be the tips to keep the code well sequenced, readable and variable names unique and understandable.
I have though of writing a function that takes the SQL as the input and gives the result, row, row count, and error as output.
What would you experienced people suggest ?
Thanks.
at first you should really try to just use relevant names for your variables.
Like if you are lookin for all the users use variables like $sqlUsers, $queryUsers, $resultUsers/$usersArray
The idea with the function would be one way to tackle the problem, as it no longer possible to code errors in the process itself, so if you do not want to switch to objectoriented programming I would probably choose that way.
Another way would be a mix, you could create only some classes in which you handle the database-interactions for specific domains. I.e. class userDataHandler would have the methods getUserById(), getAllUsers() et cetera. This way you would still have to write the querying process, but you know exactly where your queries are, have them in a structured way, there are no problems with naming your variables inside the methods, and your code doesn't get messy as you have different files for different domains -> separation of domainspecific code.
Can you explain your problem with the request-variables($_POST and $_GET) a little more? Why does your site get called with so many different variables, maybe you could structure your application a little better.

is there any shorthand method to handle loops if you know exactly how much times a loop needs to be executed

I have no problem in using loops but sometimes it really feels odd to use an separate variable just to count how many times loop has been executed especially when you know exactly how many times the loop needs to be executed just for example:
for($i=1;$i<6;$i++) echo "<input type='text' name='abc[]'/><br/>\n";
Now here I know exactly that the loop needs to do same thing 5 times so why to use an extra variable $i,initialize it,check condition each time and update it.
is there any short hand method such as:
execute(5){
echo "<input type='text' name='abc[]'/><br/>\n";}
which simply knows it have to do some work for a fixed number of times.
Currently i am familiar with these loops
for()
foreach()
while()
&
do while()
Please let me know if there exist any other.
Shortest way I can think of is using the while loop.
<?php
$i=5;
while($i--){
//Your code here
}
What you are looking for unfortunately doesn't exist.
But the idea of loops without extra variables is really great I will suggest you to submit an Idea on PHP official site So that they can create such methods in next release.
When the number of loops is known, the best option is the for loop. As your example shows, it will loop until the desired number of times, in your case 5 (the original loop and goes up 5 times for a total of 6, unless you have 7 entries in which case the 6 is your required value).
Foreach comes in handy particularly for arrays.
A while loop is used when calling information from a database.
#DigitalChris recommends str_repeat, but I think the for loop is clearer in terms of code. The best solution isn't always to be quick to do right away, it's often to be able to make quick changes if the need comes. Personal opinion, anyways.
Not as far as I know. The closest I can come is str_repeat but of course that's not what you're looking for. You could try writing a function that accepts an integer and a callable and roll your own. However, I recommend just using for loops in case other programmers have to read your code. If I need to do something five times I write:
for( $i = 0; $i < 5; $i++ ) {
// do stuff
}
That way the five is literally in the code and it's nice and readable. Your own for loop has a 6 instead of a 5, which to me makes it less readable.
As Jessica pointed out in the comments to this answer, you should really not hard code digits either way, you're better off using a constant or a parameter of some kind. That way you can improve readability even more and have a single place where you can change all occurrences of that particular "5" with some other number.

functions vs repeated code

I am writing some PHP code to create PDFs using the FPDF library. And I basically use the same 4 lines of code to print every line of the document. I was wondering which is more efficient, repeating these 4 lines over and over, or would making it into a function be better? I'm curious because it feels like a function would have a larger overhead becuse the function would only be 4 lines long.
The code I am questioning looks like this:
$pdf->checkIfPageBreakNeeded($lineheight * 2, true);
$text = ' label';
$pdf->MultiCell(0, $lineheight, $text, 1, 'L', 1);
$text = $valueFromForm;
$pdf->MultiCell(0, $lineheight, $text, 1, 'L');
$pdf->Ln();
This should answer it:
http://en.wikipedia.org/wiki/Don%27t_repeat_yourself
and
http://www.codinghorror.com/blog/2007/03/curlys-law-do-one-thing.html
Curly's Law, Do One Thing, is
reflected in several core principles
of modern software development:
Don't Repeat Yourself
If you have more than one way to express the same thing, at some point
the two or three different
representations will most likely fall
out of step with each other. Even if
they don't, you're guaranteeing
yourself the headache of maintaining
them in parallel whenever a change
occurs. And change will occur. Don't
repeat yourself is important if you
want flexible and maintainable
software.
Once and Only Once
Each and every declaration of behavior should occur once, and only
once. This is one of the main goals,
if not the main goal, when refactoring
code. The design goal is to eliminate
duplicated declarations of behavior,
typically by merging them or replacing
multiple similar implementations with
a unifying abstraction.
Single Point of Truth
Repetition leads to inconsistency and code that is subtly
broken, because you changed only some
repetitions when you needed to change
all of them. Often, it also means that
you haven't properly thought through
the organization of your code. Any
time you see duplicate code, that's a
danger sign. Complexity is a cost;
don't pay it twice.
Rather than asking yourself which is more efficient you should instead ask yourself which is more maintainable.
Writing a function is far more maintainable.
I'm curious because it feels like a
function would have a larger overhead
becuse the function would only be 4
lines long.
This is where spaghetti comes from.
Defininely encapsulate it into a function and call it. The overhead that you fear is the worst kind of premature optimization.
DRY - Don't Repeat Yourself.
Make it a function. Function call overhead is pretty small these days. In general you'll be able to save far more time by finding better high-level algorithms than fiddling with such low-level details. And making and keeping it correct is far easier with such a function. For what shall it profit a man, if he shall gain a little speed, and lose his program's correctness?
A function is certainly preferable, especially if you have to go back later to make a change.
Don't worry about overhead; worry about yourself, a year in the future, trying to debug this.
In the light of the above, Don't Repeat Yourself and make a tiny function.
In addition to all the valuable answers about the far more important topic of maintainability; I'd like to add a little something on the question of overhead.
I don't understand why you fear that a four line function would have a greater overhead.
In a compiled language, a good compiler would probably be able to inline it anyway, if appropriate.
In an interpreted language (such as PHP) the interpreter has to parse all of this repeated code each time it is encountered, at runtime. To me, that suggests that repetition might carry an even greater overhead than a function call.
Worrying about function call overhead here is ghastly premature optimisation. In matters like this, the only way to really know which is faster, is to profile it.
Make it work, make it right, make it fast. In that order.
The overhead is actually very small and wont be causing a big difference in your application.
Would u rather these small overhead, but have a easier program to maintain, or u want to save the mere millisecond but take hours to correct small changes which are repeated.
If you ask me or other developer out there, we definitely want the 1st option.
So go on with the function. U may not be maintaining the code today, but when u do, u will hate yourself for trying to save that mere milliseconds

PHP - Drilling down Data and Looping with Loops

I'm currently having difficulty finding a way of making my loops work.
I have a table of data with 15 minute values. I need the data to pull up in a few different increments
$filters=Array('Yrs','Qtr','Day','60','30','15');
I think I have a way of finding out what I need to be able to drill down to but the issue I'm having is after the first loop to cycle through all the Outter most values (ex: the user says they want to display by Hours, each hour should be able to have a "+" that will then add a new div to display the half hour data, then each half hour data have a "+" to display the 15 minute data upon request.
Now I can just program the number of outputs for each value (6 different outputs) just in-case... but isn't there a way I can make it do the drill down for each one in a loop? so I only have to code one output once and have it just check if there are any more intervals after it and check for those? I'm sure I'm just overlooking some very simple way of doing this but my brain isn't being clever today. Sorry in advance if this is a simple solution.
I guess the best way I could think of it as a reply on a form. How you would check to see if it's a reply of a reply, and then if that reply has any replys...etc for output.
Can anyone help or at least point me in the right direction? Or am I stuck coding each possible check?
Thanks in advance!
It's called "recursive" programming. Find a common theme in your values and look into writing a function that can call itself.
Check out this tutorial:
http://www.programminginterview.com/content/recursion
It basically involves taking a value, checking it conditionally, and then calling back on the function to do so again (or, in some cases, do something else with the value). It's a great way to drill down through multidimensional arrays that don't have any sort of fixed depth.

How to debug, and protect against, infinite loops in PHP?

I recently ran up against a problem that challenged my programming abilities, and it was a very accidental infinite loop. I had rewritten some code to dry it up and changed a function that was being repeatedly called by the exact methods it called; an elementary issue, certainly. Apache decided to solve the problem by crashing, and the log noted nothing but "spawned child process". The problem was that I never actually finished debugging the issue that day, it cropped up in the afternoon, and had to solve it today.
In the end, my solution was simple: log the logic manually and see what happened. The problem was immediately apparent when I had a log file consisting of two unique lines, followed by two lines that were repeated some two hundred times apiece.
What are some ways to protect ourselves against infinite loops? And, when that fails (and it will), what's the fastest way to track it down? Is it indeed the log file that is most effective, or something else?
Your answer could be language agnostic if it were a best practice, but I'd rather stick with PHP specific techniques and code.
You could use a debugger such as xdebug, and walk through your code that you suspect contains the infinite loop.
Xdebug - Debugger and Profiler Tool for PHP
You can also set
max_execution_time
to limit the time the infinite loop will burn before crashing.
I sometimes find the safest method is to incorporate a limit check in the loop. The type of loop construct doesn't matter. In this example I chose a 'while' statement:
$max_loop_iterations = 10000;
$i=0;
$test=true;
while ($test) {
if ($i++ == $max_loop_iterations) {
echo "too many iterations...";
break;
}
...
}
A reasonable value for $max_loop_iterations might be based upon:
a constant value set at runtime
a computed value based upon the size of an input
or perhaps a computed value based upon relative runtime speed
Hope this helps,
- N
Unit tests might be a good idea, too. You might want to try PHPUnit.
can you trace execution and dump out a call graph? infinite loops will be obvious, and you can easily pick out the ones that are on purpose (a huge mainloop) vs an accident (local abababa... loop or loop that never returns back to mainloop)
i've heard of software that does this for large complex programs, but i couldn't find a screenshot for you. Someone traced a program like 3dsmax and dumped out a really pretty call graph.
write simple code, so bugs will be more apparent? I wonder if your infinite loop is due to some ridiculous yarn-ball of control structures that no human being can possibly understand. Thus of course you f'ed it up.
all infinite loops aren't bad (e.g. while (!quit)).

Categories