Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In this situation, is it better to use a loop or not?
echo "0";
echo "1";
echo "2";
echo "3";
echo "4";
echo "5";
echo "6";
echo "7";
echo "8";
echo "9";
echo "10";
echo "11";
echo "12";
echo "13";
or
$number = 0;
while ($number != 13)
{
echo $number;
$number = $number + 1;
}
The former may be a little faster. The latter is a lot more readable. Choice is yours ;)
Even better would be
$totalWhatevers = 14;
for ($number = 0; $number < $totalWhatevers ; $number++)
{
echo $number;
}
Where 'totalWhatevers' is something descriptive to tell us what you are actually counting.
It's clearer to use a loop; as a rule of thumb, if you use fewer lines of code to loop, do so.
Your loop could be written more succinctly:
foreach (range(0,13) as $n)
echo $n, "\n";
I'd use a for loop, just to keep everything out in the open (your original loop seems to only print up to 12):
for ($number = 0; $number <= 13; $number++)
{
echo $number;
}
It's a lot cleaner then writing out a million 'echo', and the code is fairly self explanatory.
$string = "<?php \n";
$repeatNum = 20;
for($i = 0; $i < $repeatNum; $i++)
{
$string .= "echo \"" . $number . "\"; \n";
}
$string = "?>";
Now you can either
eval($string);
or
file_put_contents("newfile.text", $string);
and you will get a file with all the echos!
Note: This is not really a 'serious' answer. If you really want to create a PHP file with a number of echos, it works, but evaling the statement at the end is probably not the best idea for regular programming practice.
Depending on what you are trying to do, a loop could help to keep your code clearer and simpler to update.
For example, when the number of display could vary, you could use a config variables.
$repeat = 20;
for ($i = 0; $ < $repeat; ++$i) {
echo $i;
}
The mistake is in thinking that a loop generates code. This is not the case at all.
echo "0";
echo "1";
echo "2";
echo "3";
PHP will come along and execute each of these statements one by one.
for ($i = 0; $i <= 3; ++$i) {
echo $i;
}
In this case, PHP executes the same echo statement four times. Each time the end of the block is reached (a block being code between curly braces) execution jumps back to the condition. If the condition is still true, the block executes again.
Which method offers the best performance? It is very, very hard to tell.
Slowdown of method 1) The greater the range of numbers to echo, the more echo statements that have to be parsed in the script.
Slowdown of method 2) The greater the range of numbers to echo, the more times execution has to jump, the more times a condition has to be tested, and the more times a counter has to be incremented.
I do not know which scenario leads to more CPU instructions, or which leads to more memory usage. But as someone who has programmed before, I know a secret: it doesn't matter. The difference in execution will probably weigh around a few ten millionths of a second!
Therefore, the only way to make the effects become noticeable at all is if you are echoing ten million numbers, in which case one method might take a second more than the other. Isn't this a worthy gain though? No! By the time we are echoing ten million numbers, we are going to be spending minutes on either method. Only the difference between them will differ by a second, which is completely negligible. Not to mention, who knows which one is better anyhow?
As a programmer, the best thing you can do is make your code readable and maintainable. A loop is much easier to understand than a page of echo lines. With a loop I know you haven't missed any intermediate numbers, but with echoes I have to check every single line.
Technical jargon version: both algorithms have complexity O(n). There can only be a constant difference in their performance, and if that constant is not particularly large, it is negligible.
What do you mean by better? Better for the parser? better for the computer? Faster execution time? I can tell you that Making a loop is always better, For the people working with your code and for the system.
Related
I got a question about PHP/in general performance difference in the order of if / elseif / else statements.
It makes sense to run a if / elseif / else statements in order of the most often true statement at first for less checks, to improve performance.
Now my question is, what about simple if/else statements without elseif?
Does it make a difference if the statemen if is false and it jumps to the else case which actualy doesnt check anything since its the default? Or is there also an additional time added to the runtime by jumping to the else instead of inside the if statement? And if so how much of a difference does it make?
Edit:
#MonkeyZeus thanks for that term.
Yes that is part of what i mean. But in case of this:
if(x>10) {y = 10}
else {y = 0}
//or
if(x!>10) {y = 0}
else {y = 10}
does it make a difference if it jumps to the else since it checks always one statement? So if lets say case 1 happens more often, i go that way, if case 2 happens more often, i go that way with the code. The result is the same but in one way it jumps 80% of the time in the if case in the other case it jumps 80% in the else case.
As others have stated, proper benchmarking is your best way to know from a practice point of view. In theory though, there shouldn´t be any difference between your example (or any if else example) because among the many code execution optimizations, one of those is branch prediction. This will make sure that given enough iterations in a row going through the same branch of the if, execution will start predicting that further iterations will also go through that branch and start pre-executing the code from it.
As for a else if case, I´m not entirely sure but I would think it is similar if the cache prediction is done for each line of code.
At the end of the day, you are simply asking "benchmark this for me, plz."
So here you go:
PHP 7.3.5 # http://sandbox.onlinephpfunctions.com/
<?php
$x = 1;
$iterations = 10000000; // 10 million
$start = microtime(true);
for( $i = 0; $i < $iterations; ++$i )
{
}
echo microtime(true) - $start; // 0.071332216262817 seconds
echo PHP_EOL;
$start = microtime(true);
for( $i = 0; $i < $iterations; ++$i )
{
if( $x < 10 ){}
}
echo microtime(true) - $start; // 0.10689616203308 seconds
It takes about 40% more time to work through an unneeded if(){}
This question already has answers here:
Performance of FOR vs FOREACH in PHP
(5 answers)
Closed 9 years ago.
Intro
If I loop in PHP, and know how many times I want to iterate, I usually use the for-loop like this:
for($y=0; $y<10; $y++) {
// ...
}
But lately I have seen someone use the foreach-loop:
foreach (range(1, 10) as $y) {
// ...
}
Now, I found the foreach-loop much more readable and thought about adopt this foreach-construct. But on the other side the for-loop is faster as you can see in the following.
Speed Test
I did then some speed tests with the following results.
Foreach:
$latimes = [];
for($x=0; $x<100; $x++) {
$start = microtime(true);
$lcc = 0;
foreach (range(1, 10) as $y) {
$lcc ++;
}
$latimes[$x] = microtime(true) - $start;
}
echo "Test 'foreach':\n";
echo (float) array_sum($latimes)/count($latimes);
Results after I runnt it five times:
Test 'foreach': 2.2873878479004E-5
Test 'foreach': 2.2327899932861E-5
Test 'foreach': 2.9709339141846E-5
Test 'foreach': 2.5603771209717E-5
Test 'foreach': 2.2120475769043E-5
For:
$latimes = [];
for($x=0; $x<100; $x++) {
$start = microtime(true);
$lcc = 0;
for($y=0; $y<10; $y++) {
$lcc++;
}
$latimes[$x] = microtime(true) - $start;
}
echo "Test 'for':\n";
echo (float) array_sum($latimes)/count($latimes);
Results after I runnt it five times:
Test 'for': 1.3396739959717E-5
Test 'for': 1.0268688201904E-5
Test 'for': 1.0945796966553E-5
Test 'for': 1.3313293457031E-5
Test 'for': 1.9807815551758E-5
Question
What I like to know is what would you prefer and why? Which one is more readable for you, and would you prefer readability over speed?
The following code samples are written in php under codeigniter framework’s benchmark library(it just to save my time as i am currently using these :D ), if you are using other languages, consider this as a pseudo code implement in your language way. There shouldn’t be any problem to implement this to any programming language. If you have experience with php/codeigniter, then you are lucky, just copy paste this code and test :) .
$data = array();
for($i=0;$i<500000;$i++){
$data[$i] = rand();
}
$this->benchmark->mark('code_start');
for($i=0;$i<500000;$i++){
;
}
$this->benchmark->mark('code_end');
echo $this->benchmark->elapsed_time('code_start', 'code_end');
echo "<br/>";
$this->benchmark->mark('code_start');
foreach($data as $row){
;
}
$this->benchmark->mark('code_end');
I have got 2 seconds difference between these two loops(one later one ran in around 3 seconds while first one ran in around 5 seconds). So, foreach loop won the ‘battle of for vs foreach’ here. However, you might be thinking, we won’t need such big loop; May be not in all cases, but there are some cases where long loops may be needed, like update big product database from web service/xml/csv etc. And, this example is only to aware you about the performance difference between them.
But, yes, they both have some exclusive use where they should exclusively because of extreme easiness/optimization. Like, if you are working in a loop where, on a certain condition the loop can be terminated. In this case, for loop will do the work with the most flexibility. On the other hand, if you are taking every objects/item from a list array and processing them, in this case, foreach will serve you best.
I do not believe this to be a duplicate, I've looked for it, but really had no clue what to call it exactly.
I want to know why a loop that is ten times larger than another loop doesn't take ten times longer to run.
I was doing some testing to try and figure out how to make my website faster and more reactive, so I was using microtime() before and after functions. On my website, I'm not sure how to pull lists of table rows with certain attributes out without going through the entire table, and I wanted to know if this was what was slowing me down.
So using the following loop:
echo microtime(), "<br>";
echo microtime(), "<br>";
session_start();
$connection = mysqli_connect("localhost", "root", "", "") or die(mysqli_connection_error());;
echo microtime(), "<br>";
echo microtime(), "<br>";
$x=1000;
$messagequery = mysqli_query($connection, "SELECT * FROM users WHERE ID='$x'");
while(!$messagequery or mysqli_num_rows($messagequery) == 0) {
echo('a');
$x--;
$messagequery = mysqli_query($connection, "SELECT * FROM users WHERE ID='$x'");
}
echo "<br>";
echo microtime(), "<br>";
echo microtime(), "<br>";
I got the following output and similar outputs:
0.14463300 1376367329
0.14464400 1376367329
0.15548900 1376367330
0.15550000 1376367330 < these two
[a's omitted, for readability]
0.33229800 1376367330 < these two
0.33230700 1376367330
~18-20 microseconds, not that bad, nobody will notice that. So I wondered what would happen as my website grew. What would happen if I had 10 times as many (10,000) table rows to search through?
0.11086600 1376367692
0.11087600 1376367692
0.11582100 1376367693
0.11583600 1376367693
[lots of a's]
0.96294500 1376367694
0.96295500 1376367694
~83-88 microseconds. Why isn't it 180-200 microseconds? Does it take time to start and stop a loop or something?
UPDATE: To see if it was the mySQL adding variables, I tested it without the mySQL:
echo microtime(), "<br>";
echo microtime(), "<br>";
session_start();
$connection = mysqli_connect("localhost", "root", "W2072a", "triiline1") or die(mysqli_connection_error());;
echo microtime(), "<br>";
echo microtime(), "<br>";
$x=1000000;
while($x > 10) {
echo('a');
$x--;
}
echo "<br>";
echo microtime(), "<br>";
echo microtime(), "<br>";
Now it appears that at one million, it takes ~100 milliseconds(right?) and at ten million it takes ~480 milliseconds. So, my question still stands. Why do larger loops move more quickly? It's not important, I'm not planning my entire website design based off of this, but I am interested.
Normally, loops will scale linearly.
Possible bug: If you haven't already done so, consider what might happen if there was no record with id 900.
I would strongly recommend using MySQL to do your filtration work for you via WHERE clauses rather than sorting thru information this way. It's not really scalable.
Frankly, the line
while(!$messagequery or mysqli_num_rows($messagequery) == 0) {
doesn't make sense to me. $messagequery will be false if a failure occurs, and you want the loop to run as long as mysqli_num_rows($messagequery) is NOT equal to zero, I think. However, that's not what the above code does.
If mysqli_num_rows($messagequery) is equal to zero, the loop will continue.
If mysqli_num_rows($messagequery) is NOT equal to zero, the loop will stop.
See operator precedence: http://php.net/manual/en/language.operators.precedence.php
Does that help answer your question?
If you are really interested in this, you might take a look at the op codes that PHP creates. The Vulcan Logic Disassembler (VLD) might help you with this.
However, this shouldn't be your problem if you are only interested in your site speed. You won't have speed benefits/drawbacks just because of the loops themselves, but on the things they actually loop on (MySQL queries, arrays, ...).
Compare this small test script:
<pre>
<?php
$small_loop = 3000;
$big_loop = $small_loop*$small_loop;
$start = microtime(true);
// Big loop
for ($i = 0; $i < $big_loop; $i++) {
; // do nothing
}
echo "Big loop took " . (microtime(true) - $start) . " seconds\n";
$start = microtime(true);
// Small loops
for ($i = 0; $i < $small_loop; $i++) {
for ($j = 0; $j < $small_loop; $j++) {
;
}
}
echo"Small loops took " . (microtime(true) - $start) . " seconds\n";
?>
</pre>
The output for me was:
Big loop took 0.59838700294495 seconds
Small loops took 0.592453956604 seconds
As you can see the difference in 1 loop vs. 3000 loops isn't really significant.
I almost feel stupid asking such basic question, anyway.
I just started learning php on my own by reading some books, before that I used to wander from one online tutorial to another, I should have started from the very basic but I dived head first into if else, foreach, while, arrays etc.
Despite grabbing the concept of those I now realized there are few things that confuse me.
So I was doing this simple exercise, print out the numbers from 1 to 5 using ++ and the *= multiply the power of 2.
$i = 1;
echo $i.'-'.++$i.'-'.++$i.'-'.++$i.'-'.++$i;
Seems all good here, my question is why if I echo $i now it returns 5?
Do I have to reassign the 1 to $i if I want to reuse it later?
I tried to use the same pattern to echo the powers of 2 but all I got was the first and last multiplication.
$p = 1;
echo $p .'-'.$p*= 2 .'-'.$p*= 2 .'-'.$p*= 2 .'-'.$p*= 2 .'-'.$p*= 2 .'-';
Does that mean that I cannot use concatenation if I use combined operators and I would have to echo each line?
Keep in mind I'm restricted to use what is explained in the first two chapters.
Looks like you want a for loop.
$stringVar = "";
for($i=1;$i<6;$i++) {
$stringVar .= "$i -";
}
echo $stringVar;
I'll leave the second one as an exercise for you.
A simple variable (like your $i) stores one digit
so if you do a ++$i, you do the same as $i = $i +1
that means you change the content of your variable
$i = 1;
$i_originalValue = $i;
echo $i.'-'.++$i.'-'.++$i.'-'.++$i.'-'.++$i;
echo $i; //prints 5
echo $i_originalValue; //prints 1
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I have to insert a <br> tag after every 52 words so that it displays a line break otherwise the paragraph keeps going on and on increasing its width rather that the height. If there is any other, better way, please tell me.
My code
<?php
$str = "Hello world. My name is Yash Mathur and I am a student.
I need help in this question as this is getting on my nerves, so I came to
stackoverflow.com
to seek for an answer. Please help me insert a line break after every 52 characters.
Thanks in advance!";
$len = strlen($str);
if ($len > 52) {
$str = substr($str, 0, 52) . "<br>";
}
echo $str;
?>
I need to somehow put this in a loop to insert the <br> tag every 52 characters.
I assume what you are trying to achieve in the end, is just a decent-looking paragraph, whose line-length is not too long, as to become hard to read. I believe this is a cosmetic issue, that can be better addressed in the presentation layer of your application, i.e. the style sheet.
In the style belonging to the paragraph, you could just add a "width:250px" (250px is an arbitrary value) to constrain the text into a self-wrapping box that is defined by the width of the paragraph.
I would not do it in PHP unless there is a really valid reason for this, because, if you ever need to change the look of your paragraph, you would then have to delve into your PHP code. This might seem trivial now, but in a couple months you probably will not even remember writing such code in the first place. This will lead to a minor headache at best, and a great deal of wasted time searching for just this formatting function.
Please rethink your strategy.
Try using the following code:
$original = "some long string";
$parts = str_split($original, 50);
$final = implode("<br>", $parts);
You could try something like this. But this doesn't check if you're splitting a line in the middle of a word and you'll end up with an ugly output. Try using CSS instead :)
<?php
$str = "Hello world. My name is Yash Mathur and I am a student. I need help in this question as this is getting on my nerves, so I came to
stackoverflow.com to seek for an answer. Please help me insert a line break after every 52 characters. Thanks in advance!";
for ($i = 0; $i < mb_strlen($str); $i++) {
if ($i % 52){
echo mb_substr($str, 0 , 52) . '<br />';
$str = mb_substr($str, 52, mb_strlen($str));
}
}
?>
This should do the trick:
$string='Lorem ipsum...';
$parts=explode(' ',$string);
$result='';
foreach ($parts as $key=>$part)
{
$result.=$part.' ';
if ($key%50==49)
$result.='<br>';
}
However better way is to use wordwrap()
$original = "Hello world. My name is Yash Mathur and I am a student.
I need help in this question as this is getting on my nerves, so I came to
stackoverflow.com
to seek for an answer. Please help me insert a line break after every 52 characters.
Thanks in advance!";
$parts = mb_split("\s", $original);
$final = "";
$newLineCount = 10;
$wordsCount = 0;
foreach ($parts as $part) {
if($wordsCount < $newLineCount){
$final = $final . " ". $part;
$wordsCount +=1;
}else{
$final = $final . "<br>". $part;
$wordsCount = 0;
}
}
echo $final ;
output: