We've coded two validation functions, one is like below (it gets all the fields at once):
function check_fields(&$arr,&$msg,$types,$lens,$captions,$requireds) {}
and the other function is something like below:
function is_valid($field=NULL,$type=0 ,$length=0,$required=true) {}
First function has a few code lines, and reduces code lines dramatically (about 30-35 lines or even more), on the other side the second function without reference increases the code lines (about 30-35 lines or even more).
We have to call the second function for every field we want to validate, but the first function (check_fields) is vice versa.
I've read in an article long time ago that functions with reference parameters are bad from a performance point of view.
Now we don't know which function to use. Which one is better from a performance perspective?
use the solution that is simpler to use and easier to maintain.
You are talking about micro optimization, which is pretty much useless.
use references because in your case it is simpler solution and requires less code.
Well I think I got my answer myself after some web searches:
Do not use PHP references
You just remember this, when you called:
<?php
$a = 1 ;
echo "As initial, the real 'a' is..".$a."<br/>";
$b = &$a ; // it's meaning $b has the same value as $a, $b = $a AND SO $a = $b (must be)
$b += 5;
echo "b is equal to: ".$b." and a equal to: ".$a."<br/>";
echo " Now we back as initial, when a=1... (see the source code) <br/>";
$a = 1 ;
echo "After we back : b is equal to: ".$b." and a equal to: ".$a."<br/>";
echo "Wait, why b must follow a? ... <br/> ..what about if we change b alone? (see the source code)<br/>";
$b = 23;
echo "After we change b alone, b equal to: ".$b." and a equal to: ".$a."<br/>";
echo " WHAT ?? a ALSO CHANGED ?? a and b STICK TOGETHER?!! </br>" ;
echo "to 'clear this, we use 'unset' function on a (see the source code)<br/> ";
unset($a);
$b = 66;
$a = 1;
echo "Now, after unset,b is equal to: ".$b." and a equal to: ".$a."<br/>";
?>
And the Output will be:
As initial, the real 'a' is..1
After the Reference operator...(see the source code)
b is equal to: 11 and a equal to: 11
Now we back as initial... (see the source code)
After we back : b is equal to: 1 and a equal to: 1
Wait, why b must follow a? ...
..what about if we change b alone? (see the source code)
After we change b alone, b equal to: 23 and a equal to: 23
WHAT ?? a ALSO CHANGED ?? a and b STICK TOGETHER?!!
to 'clear this, we use 'unset' function on a (see the source code)
Now, after unset,b is equal to: 66 and a equal to: 1
Review:
Why did $a change? That's because & (the ampersand operator) made & as a reference variable, hence it stored in a 'temporary memory'. When you intitialized $b= &$a, see my comment $b = $a and also $a = $b, that means whenever you modified $b, $a was also modified, and vice versa. They are chained! That's the simple meaning of the reference operator.
Maybe at the beginning it feels confusing, but once you become an expert with this, you can handle this operator to make a "switching" function like this:
<?php
function bulbswitch(&$switch)
{
$switch = !$switch;
}
function lightbulb($a)
{
if ($a == true) { echo 'a is On <br/>';}
else { echo 'a is Off <br/>';}
}
$a = true ;
echo 'At the begining, a is On, then.... <br/>';
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
?>
The output will be:
At the begining, a is On, then....
a is Off
a is On
a is Off
a is On
a is Off
a is On
Related
I have seen a question on stack over flow.
What's happening with this expression? b = a + (a = a + 5)
It shows the value of b will be 15. But when i run this code on Php, value of b is 20.
Why there is difference of output in php and C#
It's happens because PHP and C# differently used memory for save variables.
Read How PHP manages variables.
So PHP not duplicated zval memory for variable "$a" and value of $a changed when ($a = $a +5) has been completed so we have that
$a = 5;
echo $a + ($a = $a + 5); //20
and C# has duplicated memory for a variables read answer What's happening with this expression? b = a + (a = a + 5).
How does the php interpret 026 and 26.
For example :
$a = 26;
echo $a; // result 26
$b = 026;
echo &b; // results in 22
Also for.
function abc() {
return (int)(0.5+029);
//return (int)(0.5+29)
}
$bac = abc();
it gives "2" and "29" does anyone knows how does return(int) works? and why does (return 029) displays "2".
P.S: Why does it says that my post does not meet quality standards and Things that i tried and proper grammat..????
When you preceed integers with zero in PHP, in that instance, 029.
It becomes octal.
So when you echo that, it will convert to its decimal form.
Which results to:
echo 029; // 2 (decimal)
Actually, its here stated in the manual
Valid octal:
octal : 0[0-7]+
I've been looking around and found formula: a = (a + b) - (b = a) it is supposed to swap two variables (or objects in some cases). However I tested it with C++ and php, these gave me different result.
php:
$a = 10;
$b = 20;
$a = ($a + $b) - ($b = $a);
echo $a, " ", $b;
This prints 20 10
C++
int a = 10;
int b = 20;
a = (a + b) - (b = a);
std::cout << a << " " << b;
This prints 10 10
Code looks the same but outputs are different, I've been thinking about two reasons:
C++ code is compiling and php is interpreting.
This formula is useless because it leads to undefined behavior.
Can somebody explains, why C++ and php output differs in this situation?
I'm not sure what the rules are in PHP, but in C++, the order of individual sub-expressions isn't strictly defined, or as the technical term is, it is "unspecified" - in other words, the compiler is allowed to calculate b = a before or after it does a + b. As long as it does a + b and b = a before the subtraction. The use of "unspecified" behaviour allows the compiler to produce more efficient code in some cases, or simply that it's possible to build a compiler for some architectures.
It also means that if you have an expression that "recalculates" a value within the expression itself, and also using it elsewhere in the expression, you get unedefined behaviour (UB for short). UB means just that, the behaviour is not defined - almost anything could happen, including what you are seeing and many other alternatives (e.g. the compiler is allowed to produce 42 as a result as well, even if logic says the answer wouldn't be 42 in this case [it's the wrong question for that!]).
I would also suggest that if you want to swap two values, in PHP:
$t = $a;
$a = $b;
$b = $t;
and in C++:
#include <algorithm>
std::swap(a, b);
or if you insist on writing your own:
int t = a;
a = b;
b = t;
Trying to be clever and perform it "without temporary variable" is almost certainly going to make it slower than the use of a temporary - certainly in a compile language like C++ - in a interpreted language like PHP, creating a new variable may add a bit of extra overhead, but it's unlikely to be that big, compared to the extra effort in the logic required.
C++ code is completely broken because of undefined behavior. (read and write b in one sequence point).
For PHP:
$a = 10;
$b = 20;
$a = ($a + $b) - ($b = $a);
//executes like thus
$a = (30) - ($b = $a);
$a = (30) - ($b = $a = 10); //new $a still not computed, using older $a
$a = (30) - (10);
$a = 20;
//then, $a=20 and $b = 10
This is totally related to Operator Precedence, this might be same in C or might not, it depends on precedence if unexpected behavior not occur.
If I try this:
$a = 0;
echo $a + ++$a, PHP_EOL;
echo $a;
I get this output:
2
1
Demo: http://codepad.org/ncVuJtJu
Why is that?
I expect to get this as an output:
1
1
My understanding:
$a = 0; // a === 0
echo $a + ++$a, PHP_EOL; // (0) + (0+1) === 1
echo $a; // a === 1
But why isn't that the output?
All the answers explaining why you get 2 and not 1 are actually wrong. According to the PHP documentation, mixing + and ++ in this manner is undefined behavior, so you could get either 1 or 2. Switching to a different version of PHP may change the result you get, and it would be just as valid.
See example 1, which says:
// mixing ++ and + produces undefined behavior
$a = 1;
echo ++$a + $a++; // may print 4 or 5
Notes:
Operator precedence does not determine the order of evaluation. Operator precedence only determines that the expression $l + ++$l is parsed as $l + (++$l), but doesn't determine if the left or right operand of the + operator is evaluated first. If the left operand is evaluated first, the result would be 0+1, and if the right operand is evaluated first, the result would be 1+1.
Operator associativity also does not determine order of evaluation. That the + operator has left associativity only determines that $a+$b+$c is evaluated as ($a+$b)+$c. It does not determine in what order a single operator's operands are evaluated.
Also relevant: On this bug report regarding another expression with undefined results, a PHP developer says: "We make no guarantee about the order of evaluation [...], just as C doesn't. Can you point to any place on the documentation where it's stated that the first operand is evaluated first?"
A preincrement operator "++" takes place before the rest of the expression it's in evaluates. So it is actually:
echo $l + ++$l; // (1) + (0+1) === 2
a + b
a = 1
b = ++a
:= 2
Why do you expect something else?
In PHP:
$a = 0;
$c = $a + ++$a;
Operator precedence visualized:
$c = ($a) + (++$a);
Evaluation sequence visualized:
$a = 0; ($a = 0)
$a = 1; (++$a)
$c = $a + $a (1 + 1);
Or written out:
The moment the sum operation is performed, $a is already 1 because ++$a has been already evaluated. The ++ operator is evaluated before the + operator.
For the fun:
$a++ + ++$a
Results in 2, too. However if you compare it as an expression, it's not equal:
$a++ + ++$a == $a + ++$a
Where as
$a++ + ++$a == $a-- + --$a
is "equal".
See Also:
Order of evaluation in PHP (Sep 2013; by NikiC) (via)
My Evaluation Order in PHP blog post explain this in detail, but here is the basic idea:
Operator precedence and associativity have nothing to do with evaluation order.
PHP does not guarantee an evaluation order. The order can change between PHP versions without notice and can also be different depending on the surrounding code.
"Normally" PHP will evaluate left-to-right, with the exception of accesses to "simple" variables (like $a). Accesses to simple variables will be executed after more complex expressions, regardless in which order the expressions actually occur.
In this particular case it means that ++$a is run first because it is a complex expression and only then the value of $a is fetched (it is already 1 at this point). So effectively you are summing 1 + 1 = 2.
The reason that simple variables are fetched after complex expressions is the Compiled Variables (CV) optimization. If you disable this optimization, for example by using the # error suppression operator, all expressions are evaluated left-to-right, including simple variable fetches.
In this particular case it means that #($a + ++$a) will result in 1, because first $a is fetched (0 at that time) and incremented only after that.
++ is the higher precedence operator, so it gets applied first.
So now l = 1.
So 1 + 1 = 2.
When you do your ++$l (preincrement), it will be done before your addition -> check operator precedence).
So, the value of $l will be 1 before your addition :
echo $l + ++$l; // $l => 1 because ++$l is done first
So your answer will be 2.
But when you do :
echo $l // you will get your first value which is $l => 1
So your answer will be 1.
This behaviour can be confirmed by inspecting how PHP compiles your script, for example:
$a = 0;
echo $a + ++$a;
Compiles into the following opcodes, which are then executed:
compiled vars: !0 = $a
line # * op fetch ext return operands
---------------------------------------------------------------------------------
1 0 > ASSIGN !0, 0
1 PRE_INC $1 !0
2 ADD ~2 !0, $1
3 ECHO ~2
4 > RETURN null
This translates to the following equivalent script:
$a = 0; // ASSIGN
$tmp = ++$a; // PRE_INC
echo $a + $tmp; // ADD, ECHO
Conclusion
By the time $a is evaluated as the left hand expression of $a + (++$a), it has already been incremented, because ++$a was evaluated first.
Obviously, this behaviour should not be relied upon; in any language for that matter.
Check the increment operator manual:
http://www.php.net/manual/en/language.operators.increment.php
Or see this codepad: http://codepad.org/Y3CnhiLx
<?php
$n = 0;
$m = 0;
echo '++ before:';
echo $n+ ++$n;
echo PHP_EOL;
echo '++ after:';
echo $m+ $m++;
echo PHP_EOL;
echo 'n:'.$n;
echo PHP_EOL;
echo 'm:'.$m;
Outputs:
++ before:2
++ after:1
n:1
m:1
As you may know we have two increment operator, one is pre-increment and second is post-increment. Pre-increment increase the value of integer before it use in expression, on the other hand post increment increase value of number after it used in expression.
suppose you have variable $a and variable $b as below
$a=0;
$b=++$a gives the value of b=1
while
$b=$a++ gives the value b=0
The output of your code varies with PHP version as seen here
Output for 4.3.0 - 5.0.5
1
1
In the above case the left hand side of + operator is evaluated first (0, 1, +).
Output for 5.1.0 - 5.5.0alpha4
2
1
In the above case the right hand side of + operator is evaluated first (1, 1, +).
This is in accordance with interjay's answer that in PHP there is no guarantee about the order of evaluation of sub-expresions. The assumption that the output could be 1, 1 is correct, so are that answers that claim that the output could be 1, 2.
First obvious part is that ++ have higher priority than +.
Second part is that php engine doesn't store value from first operand into another anonymous variable. So $l + ++$l is not an qeuivalent for
$a = $l;
$b = ++$l;
return $a + $b;
As mentioned before there is a difference in x++ and ++x. You can interpret it in the way that
x++;
increments after the semicolon
and
++x;
increments on evaluation of the expression
So it seems that your expression is evaluated from right to left
echo $l + ++$l;
Get $l: $l = 0
Apply ++: ++$l = 1
Get $l: $l = 1
Apply +: $l + $l = 1 + 1 = 2
All statements are executed from right to left.
So the value is first incremented than the value of your variable is = 1 so 1+1=2
I need help to change a character in php.
I got some code from the web:
char dest='a';
int conv=(int)dest;
Can I use this code to convert a character into numeric? Or do you have any ideas?
I just want to show the result as a decimal number:
if null == 0
if A == 1
Use ord() to return the ascii value. Subtract 96 to return a number where a=1, b=2....
Upper and lower case letters have different ASCII values, so if you want to handle them the same, you can use strtolower() to convert upper case to lower case.
To handle the NULL case, simply use if($dest). This will be true if $dest is something other than NULL or 0.
PHP is a loosely typed language, so there is no need to declare the types. So char dest='a'; is incorrect. Variables have $ prefix in PHP and no type declaration, so it should be $dest = 'a';.
Live Example
<?php
function toNumber($dest)
{
if ($dest)
return ord(strtolower($dest)) - 96;
else
return 0;
}
// Let's test the function...
echo toNumber(NULL) . " ";
echo toNumber('a') . " ";
echo toNumber('B') . " ";
echo toNumber('c');
// Output is:
// 0 1 2 3
?>
PS:
You can look at the ASCII values here.
It does indeed work as in the sample, except that you should be using php syntax (and as a sidenote: the language that code you found most probably was, it did not do the same thing).
So:
$in = "123";
$out = (int)$in;
Afterwards the following will be true:
$out === 123
This may help you:
http://www.php.net/manual/en/function.ord.php
So, if you need the ASCII code you will need to do:
$dest = 'a';
$conv = ord($dest);
If you want something like:
a == 1
b == 2
.
.
.
you should do:
$dest = 'a';
$conv = ord($dest)-96;
For more info on the ASCII codes: http://www.asciitable.com/
And for the function ord: http://www.php.net/manual/en/function.ord.php
It's very hard to answer because it's not a real question but just a little bit of it.
But if you ask.
It seems you need some translation table, that defines links between letters and numbers
A -> 2
B -> 3
C -> 4
S -> 1
or whatever.
You can achieve this by using an array, where keys would be these letters and values - desired numbers.
$defects_arr = array(
'A' -> 2,
'B' -> 3,
'C' -> 4'
'S' -> 1
};
Thus, you can convert these letters to numbers
$letter = 'A';
$number = $defects_arr($letter);
echo $number; // outputs 1
But it still seems is not what you want.
Do these defect types have any verbose equivalents? If so, why not to use them instead of letters?
Telling the whole story instead of little bit of it will help you to avoid mistakes and will save a ton of time, both yours and those who to answer.
Out of this question, if you are looking for convert RT0005 to 5
$max = 'RT0005';
return base_convert($max,10,10);
// return 5