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
Related
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;
}
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
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--.
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);
What's the difference between ++$i and $i++ in PHP?
++$i is pre-increment whilst $i++ post-increment.
pre-increment: increment variable i first and then de-reference.
post-increment: de-reference and then increment i
"Take advantage of the fact that PHP
allows you to post-increment ($i++)
and pre-increment (++$i). The meaning
is the same as long as you are not
writing anything like $j = $i++,
however pre-incrementing is almost 10%
faster, which means that you should
switch from post- to pre-incrementing
when you have the opportunity,
especially in tight loops and
especially if you're pedantic about
micro-optimisations!"
- TuxRadar
For further clarification, post-incrementation in PHP has been documented as storing a temporary variable which attributes to this 10% overhead vs. pre-incrementation.
++$i increments $i, but evaluates to the value of $i+1
$i++ increments $i, but evaluates to the old value of $i.
Here's an example:
$i = 10;
$a = $i++;
// Now $a is 10, and $i is 11
$i = 10;
$a = ++$i;
// Now $a is 11, and $i is 11
There is sometimes a slight preformance cost for using $i++. See, when you do something like
$a = $i++;
You're really doing this:
$temporary_variable = $i;
$i=$i+1;
$a=$temporary_variable;
++$i is pre-incrementation
$i is incremented
the new value is returned
$i++ is post-incrementation
the value of $i copied to an internal temporary variable
$i is incremented
the internal copy of the old value of $i is returned
++$i //first increment $i then run line
$i++ //first run line then increment $i
this example elplains simply
<?php
$x = 10;
echo $x++. ' '.$x; // the result is 10 and 11
echo '<br>';
$y = 10;
echo ++$y. ' ' .$y; // the result is 11 and 11
// so the $x++ is not showing +1 at first but the next time
// and the ++y is showing +1 first time but not increasing next
in this case there is no difference:
for($i = 0;$i<3;++$i)var_dump $i;
/*
int(0)
int(1)
int(2)
*/
for($i = 0;$i<3;$i++)var_dump $i;
/*
int(0)
int(1)
int(2)
*/
but:
for($i = 0;$i<3; $j = ++$i )var_dump($j);
/*
NULL
int(1)
int(2)
*/
for($i = 0;$i<3; $j = $i++ )var_dump($j);
/*
NULL
int(0)
int(1)
*/
Difference is: ++$i will increment $i variable and return updated value, while $i++ will return original value, so increment it.
$prefix = 1;
$postfix = 1;
echo ++$prefix; // 2
echo $postfix++; // 1
To explain jldupont's point:
$i = 1;
$x = $i++;
echo $x; // prints 1
$x = ++$i;
echo $x; // prints 3
Another way of looking at pre and post incrementing is that it's shorthand for combining 2 statements.
Pre-incrementing
// long form
$y = $y + 1;
$x = $y; // any statement using $y
// shorthand
$x = ++$y; // the same statement using $y
Post-incrementing
// long form
$x = $y; // any statement using $y
$y = $y + 1;
// shorthand
$x = $y++; // the same statement using $y
$i++ is known as post-increment. It increments the value of $i only after assigning the original value of $i to $j first.
++$i is known as pre-increment. It increments the value of $i before assigning the value to $j, so the updated value of $i will be assigned to $j.
Hence,
$i = 4;
$j = $i++;
// Now, $i = 5 and $j = 4
$i = 4;
$j = ++$i;
// Now, $i = 5 and $j = 5
These theories apply in a similar manner for decrementing as well.
Hope this helps!
It's probably best-illustrated by an example...
Post-increment:
$zero = 0;
$n = $zero++; //$n is zero
Pre-increment:
$zero = 0;
$n = ++$zero; //$n is one
Short answer:
Prefix increases the value and returns the value increased
Postfix increases the value and returns the value before it was increased
Prefix is faster
Long answer: If you think a little about it, how you would implement those yourself, you will probably realize why prefix is faster. Truth to be told, postfix is actually (often) implemented using prefix:
const T T::operator ++ (int) // postfix
{
T orig(*this);
++(*this); // call prefix operator
return (orig);
}
Avoid postfix unless you have a specific reason not to. The difference in speed can be quite a lot for complex datatypes.
I actually looked this up a few days ago. Heres my source.
The main purpose of the post-fix increment operator is usage like this:
while(*condition*)
$array[$i++] = $something;
This is a very elegant way, how to get around some array iterations.
Breakdown:
Variable $something will be assigned to the array element indexed with $i
Variable $i will be incremented
Iteration is at the end, condition will be checked
In all other cases, you should use the prefix operator. It makes the code much more clear (You can be sure, that you already work with the incremented value of particular variable).
I ran the following code to test if ++$i is 10% faster than $i++. I admit, the code does not have a stable outcome but even then I should at least have seen some numbers near the 10%. The highest I got was 4-4.5% approximately.
<?php
$randomFloat = rand(0, 10) / 10;
$before1 = microtime(true);
for($i=0; $i <1000000; ++$i){
$rand = (rand(0, 10) / 10) * (rand(0, 10) / 10);
}
$after1 = microtime(true);
echo 'it took '.($after1-$before1) . ' seconds fot ++$i<br />';
$before2 = microtime(true);
for($i=0; $i <1000000; $i++){
$rand = (rand(0, 10) / 10) * (rand(0, 10) / 10);
}
$after2 = microtime(true);
echo 'it took '.($after2-$before2) . ' seconds fot $i++<br /><br />';
echo '++$i is '.((($after1-$before1)*100)/($after2-$before2)-100).'% faster than $i++';
Both operators still do what their syntax implies: to increment. Regardless of prefix or postfix, the variable is sure to be incremented by 1. The difference between the two lies in their return values.
1. The prefix increment returns the value of a variable after it has been incremented.
2. On the other hand, the more commonly used postfix increment returns the value of a variable before it has been incremented.
// Prefix increment
let prefix = 1;
console.log(++prefix); // 2
console.log(prefix); // 2
// Postfix increment
let postfix = 1;
console.log(postfix++); // 1
console.log(postfix); // 2
To remember this rule, I think about the syntax of the two. When one types in the prefix increment, one says ++x. The position of the ++ is important here. Saying ++x means to increment (++) first then return the value of x, thus we have ++x. The postfix increment works conversely. Saying x++ means to return the value of x first then increment (++) it after, thus x++.