Shorthand For Loop in PHP - php

I have three-rows code:
echo '<div>';
for ($i=1; $i<=4; $i++) echo $i;
echo '</div>';
Is there any syntax or function let me rewrite above code in only ONE row, for example:
echo '<div>'.(for...).'</div>'; //error
Thanks

Yes its possible, no you dont want to do it:
echo '<div>' . implode('', array_keys(array_fill(1,4,0))) . '</div>';

While readability is completely personal opinion, there are "common" methods, guidelines, and coding standards which are used by a lot of developers.
And while you don't need to adhere to them, it is always up to you or the company you work for, some of these "ways" are just common sense regardless of your personal choice.
Even if there was a way to do it, why would you want to?
How far do you want to go mixing things together for supposed readability?
echo and a loop are completely different things, and should remain separate.
Answer
In answer to your question, no, it is not possible because PHP needs to differentiate between different "things" - functions, echo statements, variable declaration and usage, etc.
The only things you can "mix" are things which PHP allows to be together, like having a variable in a function parenthesis (function($someVar)).
The only thing you could do (and again this has no point, but your choice) is to put it all on one line, like so:
echo '<div>'; for ($i=1; $i<=4; $i++) { echo $i; } echo '</div>';
But that looks terrible.
I want to quickly see different things - "ah an echo, it prints out XYZ", then I want to see a loop separately so I can see easily what the loop is doing.

Related

Any reason why someone would use printf() for pretty much everything?

I am taking over a project from an existing programmer who, to be honest, left the project in a massive heap of unmaintainable, unreadable mess (edit/clarification: dozens upon dozens of standalone .php pages that are a soup of php/html/css that all reference one giant 1500 line 'functions.php' file, ack)
That being said, it seems that pretty much everywhere there is a variable, array, etc. he used printf().
For example, instead of using:
foreach($thing as $t) {
echo "<option value='".$t."'>".$t."</option>";
}
He would use something like:
foreach($thing as $t) {
printf("<option value='%s'>%s</option>", $t, $t);
}
Does anyone have any insight as to why exactly he would do this? Is there some unknown benefit that I am not aware of by using printf() instead of echo/print?
Please note that this isn't just for values that might need to be validated/scrubbed, but for EVERYTHING. Data pulled from the database, random variables and arrays that were defined elsewhere, absolutely everything is printf() instead of just echo or print, and i'm trying to figure out why he would use this method as it might help me understand the logic behind some of the things he built.
"The only reason to use printf() in preference over echo or print() is if you will be using the format string place-holders feature with additional arguments (one for each such place-holder). If not, then print() will be faster, and echo even (very slightly) faster since it does not generate a return value."
Found here: echo VS printf
I imagine he did it for code read-ability. I think using printf/sprintf is more readable than
embedding variables directly into string and alternating '"""''""''".
Personally I think this is the most readable method:
<?php foreach($thing as $t): ?>
<option value="<?php echo $t ?>"><?php echo $t ?></option>
<?php endforeach; ?>
It has the added benefit of looking nice in most IDEs
Well i would have definitely used printf in your example. I often use printf, sprintf, or strtr when outputting html elements with a lot of attributes or complex ones. Its just more readable and its much easier to swap out the values later.

php - Most frequent element in array?

This is the function:
function mostFrequent($x) {
$counted = array_count_values($x);
arsort($counted);
return(key($counted));
}
This is the call in the tag:
<?php
$x=mostFrequent(array('cheese','wine','cheese','bread','cheese','bread'));
echo "$x";
?>
This should work right? Also, how do I avoid having to use the temp $x for the echo and just echo the result of the function call directly?
Your solution seems reasonable.
<?php
echo mostFrequent(array('cheese','wine','cheese','bread','cheese','bread'));
?>
echo mostFrequent(array('cheese','wine','cheese','bread','cheese','bread'));
however, it seems wrong way and using a "temp" variable would be better.
Eventually you will learn that it is better to separate business logic from presentation logic.
So, the business of your business logic turns out to be exactly collecting these "temp" variables for the later use in the presentation logic.
also note that variables in PHP require no quotes to address. you are confusing them with strings.
echo $x;
is the proper syntax.

Do you see this breaking? any problems? simple php if elseif statement

I'm a total PHP newb, so there is probably a better way of outputting a row's class based on different variables.
Is this bad, and if it is why is it?
if ($variable1 > 0 && $variable2 != 2) {
echo "<tr class='variable1'>";
}
elseif ($variable2==2)
{
echo "<tr class='variable2'>";
}
else {
echo "<tr>";
}
The php code is syntactically correct, although the indentation seems to be messed up. The outputted HTML code is invalid though, since attributes values must be enclosed in double, not single quotes.
I'd also suggest a slight reordering:
if ($variable2 == 2) {
echo '<tr class="variable2">';
} elseif ($variable1 > 0) {
echo '<tr class="variable1">';
} else {
echo '<tr>';
}
You could put the if ($variable2==2) first and then you wouldn't need to negate it on the other if statement. Like this:
if ($variable2==2){
echo '<tr class="variable1">';
}elseif ($variable1 > 0) {
echo '<tr class="variable2">';
}else {
echo '<tr>';
}
Looks okay to me though, but it depends on the rest of the code really, you might be able to change the code slightly to make it easier to read but it looks pretty simple so, if it works, i'd keep it how it is.
I would write it like this:
$class_name = '';
if (2 == $variable2)
{
$class_name = 'variable2';
}
elseif ($variable1 > 0)
{
$class_name = 'variable1';
}
echo '<tr class="' , $class_name , '">';
notice that on the equality test I use the constant before the variable.. this is a habit so that if I miss one equal it would result in an error that I would be forced to correct it instead of a "strange" behavior
another thing is that I give the initial value to $class_name and that will be the default one
also I use apostrophes instead of quotation marks because it is faster (because the way you did it php will parse the string for variables)
and the last thing is that I echo multiple string.. that's also faster than concatenating 3 strings (
echo '<tr class="' , $class_name , '">';
and not echo
'<tr class="' . $class_name . '">';
)
Well you could start with
if ($variable2==2)
which would safe you the $variable2 != 2 if you continue with
elseif ($variable1 > 0)
but generally I see no mistake. Of course this depends on what else you want to do.
2 rules for you to learn how to program:
.1. DRY: Don't Repeat yourself.
if you have your tr tag typed 3 times, you can say for sure that's wrong.
.2. Separate business logic from presentation logic. Use templates for output. Prepare your data first and start output only if everything is ready.
So, first you have to define your variables
if ($variable2 == 2){
$class = "variable1";
}elseif ($variable1 > 0) {
$class = "variable2";
}else {
$class = "";
}
next you have to include a template and write native HTML in it, with as little PHP as possible:
<tr class="<?=$class?>">
Well, that is a really unfortunate approach at many levels, but I can tell you that even I started writing code the way you describe, only that was over 12 years ago.
I can also tell you that eventually mixing php with markup in the same files will come to bite you in the rear, and sooner than you think.
As with most things in life, getting it done faster and worrying about the rest later is a bad approch when developing in PHP.
A few pointers:
Try VERY hard to not mix PHP and HTML or other markup in the same file. Doing this will be more work when first developing but a LOT less work when changing and maintaining your code later.
PHP is an Object-oriented language. Learn how to use that to your advantage. Create libaries of your own classes for later reuse.
Use a good editor/IDE like NetBeans or Komode Editor - which are free.
The best resource for PHP info is the online PHP manual. Not only the manual pages are great, but the code snippets users contribute are full of little gems - and some glaring n00b errors too, but you will learn to filter that.
If you are new to programming in general, PLEASE do yourself a favor and get a book on programming. PHP is a very forgiving language and lets you get away with a lot of bad practices. As I said, those will come back sooner or later to get you.
After you gain some experience consider using a PHP framework, like CodeIgniter, CakePHP or ZendFramework. Try a few of them and choose the one that works for you.
Don't listen to people that tell you that PHP sucks. PHP is the most powerful programming language I have used, maybe excepting C and Prolog. The PHP array is the most powerful data structure I have encountered in any language - except linked lists in C ;-)
You CAN use PHP for every kind of programming task, including Windows and Linux server applications and full desktop graphical applications too. In fact, in my experience, PHP is faster than any dynamic language I have benchmarked it against - python, perl, ruby , tcl are all slower performing than PHP. But don't take my word for it, try it yourself :-)
A couple of links:
30+ PHP best practices for beginners
PHP bad programming practices
PHP OOP in full effect
PHP manual
echo ( ( $variable1 > 0 ) && ( $variable2 != 2 ) )
? "<tr class='variable1'>"
: ( $variable2 == 2 )
? "<tr class='variable2'>"
: "<tr>";

Why is echo faster than print?

In PHP, why is echo faster than print?
They do the same thing... Why is one faster than the other?
Do they do exactly the same thing?
echo and print are virtually (not technically) the same thing. The (pretty much only) difference between the two is that print will return the integer 1, whereas echo returns nothing. Keep in mind that neither is actually a function, but rather language constructs. echo allows you to pass multiple strings when using it as if it were a function (e.g., echo($var1, $var2, $var3)).
echo can also be shorthanded by using the syntax <?= $var1; ?> (in place of <?php echo $var1; ?>).
As far as which is faster, there are many online resources that attempt to answer that question. PHP Benchmark concludes that "[i]n reality the echo and print functions serve the exact purpose and therefore in the backend the exact same code applies. The one small thing to notice is that when using a comma to separate items whilst using the echo function, items run slightly faster."
It will really come down to your preference, since the differences in speed (whatever they actually are) are negligible.
Print always returns 1, which is also probably why it's slower
Print has a return value, this is the only difference.
The speed difference (if any) is so miniscule that it's not worth the effort thinking about micro optimisations like this, and it's absolutely not worth updating any old code to switch prints to echos. There are much better ways to speed up your site, if this is your goal.
As my experience and knowledge, You are wrong. print is faster than echo in the loops autobahn and hypertexts.
Which is faster?
I'm implementing a test that shows the difference between print and echo.
$start = microtime(1);
for($i = 0; $i < 100000; $i++)
echo "Hello world!";
echo "echo time: " . round(microtime(1) - $start, 5);
$start = microtime(1);
for($i = 0; $i < 100000; $i++)
print "Hello world!";
echo "print time: " . round(microtime(1) - $start, 5);
result:
echo time: .09
print time: .04
Another reference is phpbench that shows this fact.
Comparision
Now its time to investigate that why print is faster than echo. When you are using loops, of course, php checks if echo has multiple values to print or not, but always print can take only one parameter and it's not needed to be checked in loops. also when there are multiple values for echo bad things come through, like converting them to string and streaming them, I do believe that in huge hypertexts these problem come through too because you are forcing php to process before printing. But in small jobs like printing, only a small string echo I good (if you consider concatenations) because it doesn't return anything like print.

Differences between a while loop and a for loop in PHP?

I'm reading an ebook on PHP right now, and the author noted that the difference between a while loop and a for loop is that the for loop will count how many times it runs.
So take this:
<?php
for ($i = 1; $i < 10; $i = $i + 1) {
print "Number $i\n";
}
?>
But wouldn't this be the same as
<?php
$i = 1;
while ($i < 10) {
$i = $i + 1;
print "Number $i\n";
}
?>
Or is there some other differences that he didn't point out? (Aside from using while loop for when you're unsure of how long the condition will remain true, such as selecting rows from a database)
I mean, if that's the only difference, can't I just not use the for loop and use the while loop instead?
"For" expresses your intentions more clearly
Functionally, your two examples are the same. But they express different intentions.
while means 'I don't know how long this condition will last, but as long as it does, do this thing.'
for means 'I have a specific number of repetitions for you to execute.'
You can use one when you mean the other, but it's harder to read the code.
Some other reasons why for is preferable here
It's more concise and puts all the information about the loop in one place
It makes $i a local variable for the loop
Don't forget foreach
Personally, the loop I use most often in PHP is foreach. If you find yourself doing things like this:
for ($i=0; $i < count($some_array); $i++){
echo $some_array[$i];
}
...then try this:
foreach ($some_array as $item){
echo $item;
}
Faster to type, easier to read.
Can you? Yes, certainly. But whether or not you should is an entirely different question.
The for loop is more readable in this scenario, and is definitely the convention you'll find used within virtually every language that has looping directives. If you use the while loop, people are going to wonder why you didn't use a for loop.
Functionally, a for loop is equivalent to a while loop; that is, each can be rewritten as the other with no change to the outcome or side effects. However, each has different connotations. A while loop runs while a condition holds; the condition is static, though circumstances change. A for loop runs over a sequence. The difference is important to programmers but not programs, just as choice of variables names are important to programmers even though they can be changed to produce functionally equivalent code. One loop construct will make more sense than the other, depending on the situation.
A for-loop
for (INIT; CONDITIONS; UPDATE) {
BODY
}
is basically the same as a while-loop structured like this:
INIT
while (CONDITIONS) {
BODY
UPDATE
}
While you could technically use one or the other, there are situations where while works better than for and vice-versa.
The Main Difference Between for() and While() is that we have to define the limit or count but in while() loop we don't define limit or count it works until reached the last item
FOR LOOP
Initialization may be either in loop statement or outside the loop.
It is normally used when the number of iterations is known.
Condition is a relational expression.
It is used when initialization and increment is simple.
for ( init ; condition ; iteration )
{ statement(s); }
WHILE LOOP
Initialization is always outside the loop.
It is normally used when the number of iterations is unknown.
Condition may be expression or non-zero value.
It is used for complex initialization.
while ( condition )
{ statement(s); }
It's a matter of taste, personal preference and readability. Sometimes a while loop works better logically. Sometimes, a for.
For my personal rule, if I don't need a variable initializer, then I use a while.
But a foreach loop is useful in its own way.
Plus, in the case of PHP's scoping, where all variables not inside of functions are global, it the variable will continue living after the loop no matter which loop control you use.

Categories