I came across a very nice Fibonacci series implementation but I am having trouble understanding how exactly it works. Here are the two implementations I have tried in order to figure out the issue:
<?php
fibo(1000);
fibo2(1000);
function fibo($n){
list($a, $b) = [0, 1];
while($a<=$n){
echo $a . " ";
list($a, $b) = [$b, $a + $b];
}
echo "\n";
}
function fibo2($n){
$a = 0;
$b = 1;
while($a<=$n){
echo $a . " ";
$a = $b;
$b = $a + $b;
}
echo "\n";
}
?>
The above two functions produce the following results respectively:
fibo: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
fibo2: 0 1 2 4 8 16 32 64 128 256 512
Could you please explain why the different results occur?
Explanation repeat:
It as to do with the fact that $a loses its value when it's set to $b's value in the 2nd implementation. In the 1st implementation, the use of list() makes those inputs parameters and thus their values aren't lost when it comes to the assignment. In this case for list(), the value of $a can correctly be used in the assignment when defining $b.
For example:
function fibo2($n){
$a = 0;
$b = 1;
while($a<=$n){
echo $a . " ";
$save_a = $a;
$a = $b;
$b = $save_a + $b;
}
echo "\n";
}
fibo2(1000);
This corrects the 2nd implementation.
With the output being:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Related
In php, there is a built-in function strcmp to compare if two strings are same or not.
Returning value is integer number that if the first parameter is greater than the second I get > 0, if not < 0 and if the same 0.
So the part I don't get is comparing string as number.
Does PHP convert string to number and if so how's PHP converting?
$a = 'acorn';
$b = 'zebra';
var_dump( strcmp($a, $b) ); // -25 <- what's this number? seems like alphabetical position...nnn
Doesn't it really matter what number I get, shall I just take what it is?
Looking at the PHP: strcmp doc :
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
So yes, you can use it as it is to compare your string.
But if you want to understand the number returned by the function, it depend on the characters that makes the strings.
In ASCII :
A=65 < B=66 < C=67 ....
So if the string are different, one is gonna be greater than the other.
So you can also test it easily with a short script :
<?php
$a='A';
$b='B';
$c='C';
//Return -1 because $a is smaller than $b by one (65 < 66 )
echo strcmp($a,$b);
//Return -2 because $a is smaller than $c by two (65 < 67 )
echo strcmp($a,$c);
//Return -1 because $b is smaller than $c by one (66 < 67 )
echo strcmp($b,$c);
//Return 1 because $c is greater than $b by one (67 > 66 )
echo strcmp($c,$b);
//Return 2 because $c is greater than $a by two (67 > 65 )
echo strcmp($c,$a);
strcmp is using for comparing two strings in PHP.
If your result is greater the 0 its mean variable one ($a) is greater then Var2($b)
if return result is less then 0 its mean $b is greater and If result is equal to 0 its mean both strings are equal to each other.
$a="Hello world!";
$b= "Hello world!";
var_dump(strcmp($a, $b)); // result is 0
$a = "Hello";
$b = "Hello World";
var_dump(strcmp($a, $b)); // Outputs: -6
and If you want to see difference then you can use this
$a = 'some-content-here-example';
$b = 'some-content-example';
$asp = preg_split('//', $a, -1);
$bsp = preg_split('//', $b, -1);
$l1 = count($asp);
$l2 = count($bsp);
$length = $l1;
if ($l2 > $l1) {
$length = $l2;
}
$record = null;
$x = null;
for ($x = 0; $x < $length; $x++) {
if ($a[$x] != $b[$x]) {
if (!isset($a[$x])) {
$record.= $b[$x];
} else {
$record.= $a[$x];
}
}
}
echo $record;
This question already has answers here:
PHP operator precedence "Undefined order of evaluation"?
(3 answers)
Closed 5 years ago.
I am trying to run the following code in PHP through localhost, but its giving the unexpected output!
<?php
$a = 1;
echo ($a+$a++); // 3
?>
//answer is 3 but answer should be 2 due to post increment
here is another code and it gives the same answer! why?
<?php
$a = 1;
echo ($a+$a+$a++);
?>
//answer is still 3 !!!
The PHP manual says the following:
Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.
So what this comes down to, PHP doesn't explicitly define what the end-result is of those types of statements, and it may even change between PHP versions. We call this undefined behavior, and you shouldn't rely on it.
You might be able to find an exact reason somewhere in the source why this order is chosen, but there might not be any logic to it.
Your two examples are being evaluated as follows:
<?php
$a = 1;
echo ($a + $a++); // 3
?>
Really becomes:
<?php
$a = 1;
$b = $a++;
echo ($a + $b); // a = 2, b = 1
?>
Your second example:
<?php
$a = 1;
echo ($a + $a + $a++); // 3
?>
Becomes:
<?php
$a = 1;
$b = $a + $a;
$a++;
echo $b + $a; // 3
?>
I hope this kind of makes sense. You're right that there's no hard logic behind this.
BEHAVIOR OF INCREMENT OPERATION IN SAME LINE WITH CALCULATION IS NOT DEFINIED!
Compilator can generate different code then you expect.
Simple answer from my teacher:
NEVER USE INCREMENT/DECREMENT OPERATOR IN SAME LINE WITH CALCULATIONS!
It's behavior is undefined - computers calculate in different order then humans.
GOOD:
$d = $i++;
$i++;
for ($i = 0; $i < 5; $i++)
CAN BE A PROBLEM (you can read it wrong):
$d = $array[$i++];
WILL BE A PROBLEM:
$d = $i++ + 5 - --$k;
EDIT:
I wrote same code in C++. Checked Assembler code and result is as I said:
Math with increment is not logic for people, but you can't say that someone implemented it wrong.
As someone posted in comment:
line #* E I O op fetch ext return operands
-------------------------------------------------------------------------------------
2 0 E > ASSIGN !0, 1
3 1 POST_INC ~2 !0
2 ADD ~3 !0, ~2
3 ECHO ~3
16 4 > RETURN 1
//$a = 1;
//echo ($a+$a++);
line #* E I O op fetch ext return operands
-------------------------------------------------------------------------------------
2 0 E > ASSIGN !0, 1
3 1 ADD ~2 !0, !0
2 POST_INC ~3 !0
3 ADD ~4 ~2, ~3
4 ECHO ~4
5 > RETURN 1
//$a = 1;
//echo ($a+$a+$a++);
Translated to human language:
$a = 1;
echo ($a + $a++);
// After changing to 'computer logic' (ASM):
$c = 1; // for increment operation
$b = $a; // keep value 'before' add +1 operation
$a += $c; // add +1 operation
$d = $a + $b; // calculate value for 'echo'
echo $d; // print result
Its because the ++ sign is an incremental operator to a variable. So your
$a = 1
$a++ = 2
($a+$a++) = (1+2) = 3
Thats why it shows 3 as the answer.
I am working on a function, but that function is not working properly when
I run it, then it runs continuously.
I didn't find where is actual problem is.
<?php
function recursion($a) {
if($a < 20) {
echo "$a\n";
recursion($a);
}
}
$a = 2;
recursion($a);
echo "</br>";
?>
Your recursion function going to infinite because you are passing same value again and again with recursion($a); so if($a<20) will be always result true and recursion won't break ever.
Try increment ++$a or $a += 1 or $a = $a+1.
recursion(++$a);//increasing value with prefix operator ++
Complete code:
function recursion($a) {
if($a < 20) {
echo "$a\n";
recursion(++$a);
}
}
$a = 2;
recursion($a);
echo "</br>";
Output:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
I would like to achieve the following: I have a variable A with a value from 1 - 1000. For every 100 the value reaches, a second variable B should get added +1. A third variable C should echo all number of variable A which are less than 100
For example:
$a = 10
$b = 0
$c = 10
$a = 100
$b = 1
$c = 00
$a = 110
$b = 1
$c = 10
$a = 1530
$b = 15
$c = 30
What's the best way to achieve that in PHP? Use str_split() oder count()?
$b = floor($a/100);
$c = $a % 100;
echo 'wow, that was easy';
Which construction is faster:
$a = $b * $c ? $b * $c : 0;
or
$i = $b * $c;
$a = $i ? $i : 0;
All variables are local ones.
Does speed differs for mulitplication, addition, substraction and division?
Update:
Here's some clarification:
This is a theoretical question about writing speed-optimized code from scratch. Not about "searching bottlenecks".
I can measure code speed by myself. But it's was not a question about homework of using microtime(). It was a question about how PHP-interpreter works (what I tried to figure out by digging google myself but was unseccusfull).
Moreover - I did measuring with myself and was a little confused. Different starting values of $a, $b and $c (combinations of zeros, negative, positive, integer and floats) produce different results between constructions. So I was confused.
BoltClock provide me usefull info but user576875 made my day by posting a link to opcode decoder! His answer contains also direct answer to my question. Thanks!
If you have PHP 5.3, this is faster:
$a = $b * $c ?: 0;
This is the same as $a = $b * $c ? $b * $c : 0;, but the $a*$b calcultation is done only once. Also, it doesn't do additional assignments as in your second solution.
Using Martin v. Löwis's benchmark script I get the following times:
$a = $b * $c ?: 0; 1.07s
$a = $b * $c ? $b * $c : 0; 1.16s
$i = $b * $c; $a = $i ? $i : 0; 1.39s
Now these are micro-optimizations, so there is probably many ways of optimizing your code before doing this :)
If it is not the case, you may also want to compare generated PHP OP codes:
1 $a = $b * $c ? $b * $c : 0; :
number of ops: 8
compiled vars: !0 = $a, !1 = $b, !2 = $c
line # op fetch ext return operands
-------------------------------------------------------------------------------
1 0 MUL ~0 !1($b), !2($c)
1 JMPZ ~0, ->5
2 MUL ~1 !1($b), !2($c)
3 QM_ASSIGN ~2 ~1
4 JMP ->6
5 QM_ASSIGN ~2 0
6 ASSIGN !0($a), ~2
7 RETURN null
2 $i = $b * $c; $a = $i ? $i : 0;
number of ops: 8
compiled vars: !0 = $i, !1 = $b, !2 = $c, !3 = $a
line # op fetch ext return operands
-------------------------------------------------------------------------------
1 0 MUL ~0 !1($b), !2($c)
1 ASSIGN !0($i), ~0
2 JMPZ !0($i), ->5
3 QM_ASSIGN ~2 !0($i)
4 JMP ->6
5 QM_ASSIGN ~2 0
6 ASSIGN !3($a), ~2
7 RETURN null
3 $a = $b * $c ?: 0; :
number of ops: 5
compiled vars: !0 = $a, !1 = $b, !2 = $c
line # op fetch ext return operands
-------------------------------------------------------------------------------
1 0 MUL ~0 !1($b), !2($c)
1 ZEND_JMP_SET ~1 ~0
2 QM_ASSIGN ~1 0
3 ASSIGN !0($a), ~1
4 RETURN null
These OP code listings was generated by the VLD extension.
<?php
function run(){
$b=10;
$c=10;
$start=gettimeofday(TRUE);
for($k=0;$k<10000000;$k++){
$a = $b * $c ? $b * $c : 0;
}
printf("%f\n", gettimeofday(TRUE)-$start);
$start=gettimeofday(TRUE);
for($k=0;$k<10000000;$k++){
$i = $b * $c;
$a = $i ? $i : 0;
}
printf("%f\n", gettimeofday(TRUE)-$start);
}
run();
?>
On my system (PHP 5.3.3, Linux, Core i7 2.8GHz), I get
1.593521
1.512892
So the separate assignment is slightly faster. For addition, (+ instead of *), I get the reverse result:
1.386522
1.450358
So you really need to measure these on your own system - with a different PHP version, the outcome may change again.
Your two pieces of code have a drawback each. One does an additional assignment; the other does an additional mathematical operation. Best would be to do neither, which, with the ternary operator in PHP 5.3, you can:
$a = $b * $c ?: 0;
Omitting the second part of the ternary causes PHP to put the result of the first part there instead.
Using Martin v. Löwis's benchmarking code, I reckon this is about 25% faster than either.