Why does this output 19? - php

It is not clear the logic behind this PHP code to give out the answer 19. How can the answer be 19? What is the logic?
$i=5;
$i +=$i++ + ++$i;
echo $i;

$i=5;
$i +=$i++ + ++$i;
^
Take value of $i as 5 then increment to 6
^
increment value of $i from 6 to 7, and use the 7
^
5 + 7 = 12
^ $i is already 7, because of the increments in the previous operations,
so add the 12 we've just calculated, giving 19

First, let's consider the following code:
<?php
$e = 0;
$e += ++$e;
echo $e;
Will the output be 2, or will it be 1?
One the second line, the right hand side of the equation ++$e; will increment the value of $e, making $e (temporarily) equal 1.
When the left hand side of the equation is run, $e equals 1 already, so 1 will be added the that value, so essentially, the line really says $e = 1 + 1.
<?php
$e = 0;
$e = 1 + 1;
echo $e;
When we do the same with the equation given earlier,
$i=5;
$i +=$i++ + ++$i;
echo $i;
The importance here is post and pre incrementing.
++i increments i and evaluates to the new value of i.
i++ evaluates to the old value of i, and increments i.
When $i += $i++ + ++$i; is calculated, on the Right Hand Side, ++$i (which will be 5) and $i++ (which will be 7).
$i += 5 + 7 (which becomes 7 + 5 + 7) means that $i will equal 19.

$i += $i++ + ++$i ;
$i = $i + ($i+1 + 1+$i);
19 = 7 + (5 + 7);

Related

How do I square a number using a for loop in php?

My task, using php, is to create a random number, then make that number multiply itself. However i cannot use the multiply operator (*) and have been told to create a for loop instead however I'm having some troubles.
$startNum = rand(1,10);
for ($i = $startNum; $i <= 10; $i++)
{
echo $i;
}
This is what i have so far, however this is completely wrong and will only get a random number and count to 10 from it.
Any help would be very appreciated, thanks.
When squaring you are just multiplying a number by itself, another way to do this is through addition, add a number to itself x amount of times. So, with 4 squared, that is 4 * 4 or, 4 + 4 + 4 + 4.
Doing this in a for loop should be as simple as
$startNum = rand(1,10);
$endNum = 0;
for ($i = 0; $i < $startNum; $i++)
{
$endNum += $startNum;
}
echo $endNum;
Caveat: I don't program Php so forgive syntax errors.
$startNum*$startNum means that the loop should loop $startNum times and in each iteration add $startNum, i.e., the number itself
$s = 0;
for($i=1;$i<=$startNum;$i++){
$s += $startNum;
}
echo $s;
Still not using the multiplication operator :p
$n = mt_rand(1, 10);
echo array_sum(array_fill(0, $n, $n));
you can do this by simple addition(+) operator
square means add that number into same number for same time.
example : square of 2 means : 2+2;
square of 4 means : addition of 4 with 4 for 4 times : 4+4+4+4
so you can do like that
$startNum = rand(1,10);
$ans=0;
for ($i = 0 ;$i < $startNum; $i++)
{
echo $ans+=$startNum;
}

Decoding function to better understand

I am revisiting PHP and want to relearn where i lack and i found one problem, i am unable to understand the following code, where as it should output 6 according to the quiz, i got it from but i broke it down to simple pieces and commented out to better understand, according to me the value of $sum should be 4, but what i am doing wrong, maybe my breakdown is wrong?
$numbers = array(1,2,3,4);
$total = count($numbers);
//$total = 4
$sum = 0;
$output = "";
$i = 0;
foreach($numbers as $number) {
$i = $i + 1;
//0+1 = 1
//0+2 = 2
//0+3 = 3
//0+4 = 4
if ($i < $total) {
$sum = $sum + $number;
//1st time loop = 0 < 4 false
//2nd time loop = 0 < 1 false
//3rd time loop = 0 < 2 false
//5th time loop = 0 < 3 false
//6th time loop = 4 = 4 true
//$sum + $number
//0 + 4
//4
}
}
echo $sum;
This is very basic question and might get down vote but it is also a strong backbone for people who want to become PHP developer.
You don't understand the last part in the loop. It actually goes like this now:
if($i < $total) {
$sum = $sum + $number;
//1st time loop: $sum is 0. $sum + 1 = 1. $sum is now 1.
//2nd time loop: $sum is 1. $sum + 2 = 3. $sum is now 3.
//3rd time loop: $sum is 3. $sum + 3 = 6. $sum is now 6.
//4th time loop: it doesn't get here. $i (4) < $total (4)
//This is false, so it doesn't execute this block.
}
echo $sum; // Output: 6
I altered your script a little so that it will print out what it's doing as it goes. I find it useful to do this kind of thing if I'm having a hard time thinking through a problem.
$numbers = array(1,2,3,4);
$total = count($numbers);
$sum = 0;
$i = 0;
$j = 0;
foreach($numbers as $number) {
$i = $i + 1;
echo "Iteration $j: \$i +1 is $i, \$sum is $sum, \$number is $number";
if ($i < $total) {
$sum = $sum + $number;
echo ", \$i is less than \$total ($total), so \$sum + \$number is: $sum";
} else {
echo ", \$i is not less than \$total ($total), so \$sum will not be increased.";
}
echo '<br>'; // or a new line if it's CLI
$j++;
}
echo $sum;
Lets Explain
Your initial value of $i is 0 but when you start looping you increment it by 1, so the start value of $i is 1.
When checking the condition you did't use equal sign to check for the last value whether you start value is 1. So its clear that your loop must be run for 1 less of total.
$i = 0;
foreach($numbers as $number) {
$i += 1;
if ($i < $total)
$sum += $number;
}
echo $sum;
Analysis
Step: 1 / 4
The value of $number is: 1 And The value of $i is: 1
Step: 2 / 4
The value of $number is: 2 And The value of $i is: 2
Step: 3 / 4
The value of $number is: 3 And The value of $i is: 3
When the loop again go for a check the value of $i increased by 1 and at 4. So trying to match the condition if ($i < $total), where the value of $i and $total is equal, so it will return false. So the loop only run for 3 time.
Result
6

Difference $i++ and ++$i when 0

I came along this script lately:
$i = 0;
$x = $i++; $y = ++$i;
print $x; print $y;
The output was 02. I can imagine that you can't count +1 on $i with ++ while it is 0, but why does $y output as 2? And why isn't the output 11 or 01?
post increment vs pre increment.
Post: Trailing $i++ means that $i is returned and then incremented after.
Pre: Preceding ++$i means that $i is incremented and that result is returned.
So $x is set to 0 (the initial value of $i) and then incremented. $i is now equal to 1. Then $i is incremented again to 2 and that value is set in $y. So in the end, $x=0 and $y=2 and $i=2. Your code could be rewritten as:
$i=0;
//x, post increment, set x to i then increment after.
$x=$i;
$i=$i+1;
//y, pre increment, increment first and then set y to i.
$i=$i+1;
$y=$i;
Same thing applies to the decrement operator --$i and $i--.

Incrementing numbers doesn't give an error

How come this code below echo's 2 and does not give an error, does it just ignore +1+2+3+4 ?
I've searched but couldn't find an answer.
<?php
$i = 1;
$i+++1+2+3+4;
echo $i;
That line:
$i+++1+2+3+4;
Says:
Increment $i
Add the value of $i pre increment to +1+2+3+4, but don't store the result anywhere.
Hence $i == 2.
If you wouldn't want it to be ignored, you should store the result:
$i = $i+++1+2+3+4;
You never assign the completed operation anywhere:
These two are functionally equivalent:
$i++;
$i = $i + 1;
both will increment $i by 1, and save that incremented value in $i
With $i+++1+2+3+4 you're essentially executing
($i++) + 1 + 2 + 3 + 4
which is
$i = $i + 1;
1 + 2 + 3 + 4; // useless, result not stored anywhere
so which increments $i by 1, saves that to $i, then does the other additions. But since those aren't being saved anywhere, the result is thrown away.
if you had
php > $i = 1;
php > $i = $i+++1+2+3+4;
^^^^^----add this
php > echo $i;
11
then it would have worked as you expect.
All is fine. You just forgot the assignment, so i is affected only by ++ operator:
<?php
$i = 1;
$x = $i+++1+2+3+4;
echo "{$i} vs "{$x}";
would return
2 vs 11
$i++ means add 1 to $i.
and like python, the +1+2+3+4 means add the value of $i pre increment to +1+2+3+4 but don't store it anywhere.(so no memory address or anything like that...).
so what you get is just $i==2

what does a comma do in the first parameter of a for loop?

What does it mean when there is a comma in the first parameter of a for loop?
For example:
for ($j=0, $n2=sizeof($quotes[$i]['methods']); $j<$n2; $j++) {
//
}
A comma in the first section of the loop just separates variable declarations.
Essentially it is just declaring two variables $j=0 and $n2=sizeof($quotes[$i]['methods']), but in the loop constructor instead of before the loop constructor.
PHP inherited C++-like syntax.
It is common for C++-like languages to have scope visibility for code blocks or control structures, like:
#include <iostream>
using namespace std;
int main() {
int a = 0; // main scope;
int b = 5; // main scope;
if(a != b){
int c = a + b; // if scope;
// a, b, c visible.
}
// a and b visible, but c - not visible.
for(int i = 10; i < 20; i++){
// for-loop scope:
// i, a and b visible
cout << "i: " << i << endl;
}
// a and b visible, but i - not visible.
return 0;
}
PHP has no such feature, but inherited syntax rules (and most of C++ code conventions).
<?php
header('Content-Type: text/plain');
for($i = 0, $j = 10; $i < 10; $i++, $j += 2){
echo "{$i} + {$j} = ", $i + $j, PHP_EOL;
}
?>
is equival to
<?php
header('Content-Type: text/plain');
$j = 10;
for($i = 0; $i < 10; $i++){
echo "{$i} + {$j} = ", $i + $j, PHP_EOL;
$j += 2;
}
?>
Variables $i and $j will be accessible everywhere after for-loop, but declaring them in for-loop header section might be done for obviosity (some people say, that those variables are definately used in this cycle). Also it is shorter.
NOTE: You may use , for every header section of for-loop too.
UPDv1:
for-loop declaration:
for(initialization_section; condition_section; post_execution_section){
// actions
}
Each of sections might contain expression, but can not contain other control structures.
1) initialization_section:
Should contain expressions to execute before loop starts.
If there is more than one separate expression, they should be separated by comma ,.
Executes before any of for-loop iterations.
for($i = 0, $j = 1; $i < 10; $i++){
echo "{$i} + {$j} = ", $i + $j, PHP_EOL;
}
Result:
0 + 1 = 1
1 + 1 = 2
2 + 1 = 3
3 + 1 = 4
4 + 1 = 5
5 + 1 = 6
6 + 1 = 7
7 + 1 = 8
8 + 1 = 9
9 + 1 = 10
2) condition_section:
Should contain expressions to check if loop continues or stops. If there is more than one separate action, they should be separated by comma ,.
Executes before every for-loop iteration.
for($i = 1, $j = 0; $i++, $j < 10; $j++){
echo "{$i} + {$j} = ", $i + $j, PHP_EOL;
}
Result:
2 + 0 = 2
3 + 1 = 4
4 + 2 = 6
5 + 3 = 8
6 + 4 = 10
7 + 5 = 12
8 + 6 = 14
9 + 7 = 16
10 + 8 = 18
11 + 9 = 20
Comma in this section of for-loop causes ignore of all previous expressions of this section, except the last one (as #icktoofay mentioned).
for($i = 0, $j = 1; $i < 1, $j < 5; $i++, $j++){
echo "{$i} + {$j} = ", $i + $j, PHP_EOL;
}
Result:
0 + 1 = 1
1 + 2 = 3
2 + 3 = 5
3 + 4 = 7
Regardless of $i < 1 is false for the second iteration. It might be used as default pre-execution statement.
3) post_execution_section:
Should contain expressions to execute after loop body actions are performed. If there is more than one separate action, they should be separated by comma ,.
Executes after every for-loop iteration.
for($i = 0; $i < 10; $i++, $i *= 2){
echo $i, PHP_EOL;
}
Result:
0
2
6
Also, each of for-loop sections might be empty (do nothing) with preserve of semicolon ; separators:
for(;;){
// infinite loop
}

Categories